How to correctly use a fixed size thread pool?

I am quite new to using concurrency in Java, so please forgive if this is a trivial question.
I would like to make use of something like pool=Executors.newFixedThreadPool(n) to automatically use a fixed number of threads to process pieces of work. I understand that I can asynchronously run some Runnable by one of the threads in the threadpool using pool.execute(someRunnable).
My problem is this: I have some fixed amount of N datastructures myDS (which are not reentrant or sharable) that get initialized at program start and which are needed by the runnables to do the work. So, what I really would like to do is that I not only reuse N threads but also N of these datastructures to do the work.
So, lets say I want to have 10 threads, then I would want to create 10 myDS objects once and for all. Each time some work comes in, I want that work to get processed by the next free thread, using the next free datastructure. What I was wondering is if there is something in the library that lets me do the resusing of threads AND datastructures as simply as just reusing a pool of threads. Ideally, each thread would get associated with one datastructure somehow.
Currently I use an approach where I create 10 Runnable worker objects, each with its own copy of myDS. Those worker objects get stored in an ArrayBlockingQueue of size 10. Each time some work comes in, I get the next Runner from the queue, pass it the piece of work and submit it to the thread pool.
The tricky part is how to get the worker object back into the Queue: currently I essentially do queue.put(this) at the very end of each Runnable's run method but I am not sure if that is safe or how to do it safely.
What are the standard patterns and library classes to use for solving this problem correctly?

Thank you for that feedback!
There is one issue that worries me though and I obviously do not understand it enough: as I said I hand back the Runnable to the blocking queue at the end of the Runnable.run method using queue.put(this). This is done via a static method from the main class that creates the threads and runnable objects in a main method. Originally I tried to make that method for putting back the Runnable objects serialized but that inevitably always led to a deadlock or hang condition: the method for putting back the runnable was never actually run. So I ended up doing this without serializing the put action in any way and so far it seems to work ... but is this safe?
To reiterate: I have a static class that creates a thread pool object and a ArrayBlockingQueue queue object of runnable objects. In a loop I use queue.take() to get the next free runnable object, and pass this runnable to pool.execute. Inside the runnable, in method run, i use staticclass.putBack(this) which in turn does queue.put(therunnableigot). Can I trust that this queue.put operation, which can happen from several threads at the same time works without problem without serializing it explicitly? And why would making the staticclass.putBack method serialized cause a hang? I also tried to serialize using the queue object itself instead of the static class, by doing serialize(queue) { queue.put(therunnable) } but that also caused a hang. I have to admit that I do not understand at all why that hang occurred and if I need the serialization here or not.

Similar Messages

  • Fixed Size Thread Pool which infinitely serve task submitted to it

    Hi,
    I want to create a fixed size thread pool say of size 100 and i will submit around 200 task to it.
    Now i want it to serve them infinitely i.e once all tasks are completed re-do them again and again.
    public void start(Vector<String> addresses)
          //Create a Runnable object of each address in "addresses"
           Vector<FindAgentRunnable> runnables = new Vector<FindAgentRunnable>(1,1);
            for (String address : addresses)
                runnables.addElement(new FindAgentRunnable(address));
           //Create a thread pool of size 100
            ExecutorService pool = Executors.newFixedThreadPool(100);
            //Here i added all the runnables to the thread pool
             for(FindAgentRunnable runnable : runnables)
                    pool.submit(runnable);
                pool.shutdown();
    }Now i wants that this thread pool execute the task infinitely i.e once all the tasks are done then restart all the tasks again.
    I have also tried to add then again and again but it throws a java.util.concurrent.RejectedExecutionException
    public void start(Vector<String> addresses)
          //Create a Runnable object of each address in "addresses"
           Vector<FindAgentRunnable> runnables = new Vector<FindAgentRunnable>(1,1);
            for (String address : addresses)
                runnables.addElement(new FindAgentRunnable(address));
           //Create a thread pool of size 100
            ExecutorService pool = Executors.newFixedThreadPool(100);
            for(;;)
                for(FindAgentRunnable runnable : runnables)
                    pool.submit(runnable);
                pool.shutdown();
                try
                    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
                catch (InterruptedException ex)
                    Logger.getLogger(AgentFinder.class.getName()).log(Level.SEVERE, null, ex);
    }Can anybody help me to solve this problem?
    Thnx in advance.

    Ravi_Gupta wrote:
    *@ kajbj*
    so what should i do?
    can you suggest me a solution?Consider this thread "closed". Continue to post in your other thread. I, and all others don't want to give answers that already have been given.

  • Fixed size thread pool excepting more tasks then it should

    Hello,
    I have the following code in a simple program (code below)
              BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10, false);
              ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, 10, 20, TimeUnit.SECONDS, q);
    for (int x = 0; x < 30; x++) {
    newPool.execute(new threaded());
    My understanding is that this should create a thread pool that will accept 10 tasks, once there have been 10 tasks submitted I should get RejectedExecutionException, however; I am seeing that when I execute the code the pool accepts 20 execute calls before throwing RejectedExecutionException. I am on Windows 7 using Java 1.6.0_21
    Any thoughts on what I am doing incorrectly?
    Thanks
    import java.util.concurrent.*;
    public class ThreadPoolTest {
         public static class threaded implements Runnable {
              @Override
              public void run() {
                   System.out.println("In thread: " + Thread.currentThread().getId());
                   try {
                        Thread.sleep(5000);
                   } catch (InterruptedException e) {
                        System.out.println("Thread: " + Thread.currentThread().getId()
                                  + " interuptted");
                   System.out.println("Exiting thread: " + Thread.currentThread().getId());
         private static int MAX = 10;
         private Executor pool;
         public ThreadPoolTest() {
              super();
              BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(MAX/2, false);
              ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, MAX, 20, TimeUnit.SECONDS, q);
              pool = newPool;
         * @param args
         public static void main(String[] args) {
              ThreadPoolTest object = new ThreadPoolTest();
              object.doThreads();
         private void doThreads() {
              int submitted = 0, rejected = 0;
              for (int x = 0; x < MAX * 3; x++) {
                   try {
                        System.out.println(Integer.toString(x) + " submitting");
                        pool.execute(new threaded());
                        submitted++;
                   catch (RejectedExecutionException re) {
                        System.err.println("Submission " + x + " was rejected");
                        rejected++;
              System.out.println("\n\nSubmitted: " + MAX*2);
              System.out.println("Accepted: " + submitted);
              System.out.println("Rejected: " + rejected);
    }

    I don't know what is wrong because I tried this
    public static void main(String args[])  {
        BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10, false);
        ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, 10, 20, TimeUnit.SECONDS, q);
        for (int x = 0; x < 100; x++) {
            System.err.println(x + ": " + q.size());
            newPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Thread.sleep(1000);
                    return null;
    }and it printed
    0: 0
    1: 0
    2: 1
    3: 2
    4: 3
    5: 4
    6: 5
    7: 6
    8: 7
    9: 8
    10: 9
    11: 10
    12: 10
    13: 10
    14: 10
    15: 10
    16: 10
    17: 10
    18: 10
    19: 10
    20: 10
    Exception in thread "main" java.util.concurrent.RejectedExecutionException
         at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1768)
         at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)
         at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)
         at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:92)
         at Main.main(Main.java:36)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)Ihave Java 6 update 24 on Linux, but I don't believe this should make a difference. Can you try my code?

  • How to correctly use ThinkVantage System Update?

    Hello,
    I have ThinkPad E520 for two months and I still don't know how to correctly use System Update. From the beginning I've downloaded and installed all updates, but now I want to do it right. How do you do it? Do you install only updates that you need? Or all updates of program that you use? Or just all updates that System Update offers?
    Here is interesting sentence: "If it's not broken, don't fix it!". So how?
    I don't want to risk and do unnecessary things... But there is a problem with me, that I don't know, which update do I need... So I really need know, how to do it correctly...
    Thank you.

    Do only use System Update if you have problems with a driver or Thinkvantage Tool - feature.
    In my company we never used System update and the laptops are running without any changes (except Windows update) since 5 to 6 years. So i have removed TVSU from all computers.
    System Update is a very excellent tool after a clean install from a Windows CD/DVD to install all Lenovo drivers and tools you want to use. A disadvantage of cyclic updates via System Update is, that parts of old drivers in most cases will be kept because the newer driver will be installed over the old one in most cases, which leads after several updates to an instability of the system.
    Just my private opinion...
    My home-forum: http://www.thinkpad-forum.de
    Wiki: Deutsches ThinkPad-Wiki English ThinkWiki
    My ThinkPad-Collection

  • How do I use Tooltip in a thread?

    Hello Everyone.
    I'm trying to use Tooltip in a (added) thread, but I've got IlligalStateException.
    Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            Tooltip tooltip = new Tooltip();
            return null;
    new Tread(task).start();NetBeans 7.1
    JDK 1.6.0_30
    JavaFX 2.0.1
    I can use other controls (like Button, etc).
    Thank you in advance.

    How do I use Tooltip in a thread? You can only create Tooltips on the JavaFX Application Thread due to this bug: http://javafx-jira.kenai.com/browse/RT-17716

  • [svn:osmf:] 14036: Tweaking sample to have the parallel element use a fixed size.

    Revision: 14036
    Revision: 14036
    Author:   [email protected]
    Date:     2010-02-08 06:31:10 -0800 (Mon, 08 Feb 2010)
    Log Message:
    Tweaking sample to have the parallel element use a fixed size.
    Modified Paths:
        osmf/trunk/apps/samples/framework/LayoutSample/src/LayoutSample.as

    Hi,
    thank you for your fast reply. Please find attached my code where I marked the array creation with green circles and the control part with a red one. I removed all the other stuff and loops which are not relevant here (heart beat loop, value initialization, DMA fifo, etc). The sampling rate should be up to 50kS/s for capturing signals with a frequency of the range of 10 to 500Hz).
    @ Spectre Dave:
    I would like to do it in the FPGA because my host part (cRIO PPC) is already overloaded and I had a lot of problems to get it running and save the data to a file with the high sampling rate (50kS/s). I was thinking that simple array functions would be an easy thing for an FPGA. Or am I wrong??
    Please let me know if you have any idea or if you need more information.
    Thank you very much and best regards
    Andreas
    Attachments:
    FPGAarrayProblem.png ‏189 KB

  • How do I set a fixed size for a window (frame) :P

    hello!
    Was wondering if I can set fix dimensions (size) for a window(frame) in Java.
    Background: I have a menu and when I click on one of the options a window opens but I hate the fact that I can enlarge it...wish it would be fixed sized and have scroll instead... :P
    any ideas?
    many thanks!
    Cristina

    sorry for not using the swing forum but i considered java programming forum as more or less enclosing all problems Do you understand how to use forums? First you should be searching the forums to see if you questions has been asked and answered before. (Very few questions posted in the forums are original). It makes sense to search the forum where the questions should have been posted in the first place.
    For example, if you had searched the Swing forum using "fixed size jframe" you would have found this posting at the top of the search results:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=712407
    So you would have had your question answered in less than a minute and we wouldn't have wasted time answering a question that has already been answered.
    A win-win situtation for everybody.

  • How can free + used space tbs size, can someone explain

    Hi Gurus
    Can someone explain this, How can free + used space in a tablespace can be greater than size of a tablespace. What am I missing here . Thanks a lot .
    I am on 10.2.0.1, HP-UX
    14:38:52 SQL> select owner,sum(bytes), sum(BYTES) /1024/1024 "MB" from dba_segments where tablespace
    name='USERDB1ADATA' group by owner;
    OWNER SUM(BYTES) MB
    USERDB1A 839680000 800.78125
    1 row selected.
    14:40:42 SQL> select bytes, BYTES /1024/1024 "MB" from dba_data_files where tablespace_name='USERDB1
    A_DATA';
    BYTES MB
    3758096384 3584
    1 row selected.
    14:40:42 SQL> select sum(bytes) , sum(BYTES) /1024/1024 "MB"from dba_free_space where tablespace_nam
    e='USERDB1A_DATA';
    SUM(BYTES) MB
    3067412480 2925.3125
    1 row selected.
    14:40:43 SQL> select 839680000 + 3067412480 "used + free space" from dual;
    used + free space
    3907092480
    1 row selected.
    New DBA

    Good point, Howard, about the recycle bin. So I cleaned up, recreated the table, filled it, dropped it but did not purge it, and ...
    SQL> create table test.x tablespace test as select * from dba_objects where 1=2;
    Table created.
    SQL> insert into test.x select * from dba_objects;
    12617 rows created.
    SQL> commit;
    Commit complete.
    SQL> drop table test.x;
    Table dropped.
    SQL> with
      2  dbf_size as (select sum(bytes) size_
      3                 from dba_data_files where tablespace_name='TEST'),
      4  dbf_free as (select sum(bytes) free_
      5                 from dba_free_space where tablespace_name='TEST'),
      6  dbf_used as (select sum(bytes) used_
      7                 from dba_segments where tablespace_name='TEST')
      8  select size_, free_, used_, (size_ - free_ - used_) left_
      9         from dbf_size, dbf_free, dbf_used
    10  /
         SIZE_      FREE_      USED_      LEFT_
       5242880    5177344    2162688   -2097152
    SQL>and then I played around with my SQL and came up with
    WITH
    dbf_size AS (SELECT SUM(bytes) size_
                   FROM dba_data_files
                  WHERE tablespace_name='TEST'),
    dbf_free AS (SELECT SUM(bytes) free_
                   FROM dba_free_space
                  WHERE tablespace_name='TEST'),
    dbf_used AS (SELECT SUM(bytes) used_
                   FROM dba_segments
                  WHERE tablespace_name='TEST'),
    dbf_fbin AS (SELECT SUM(bytes) fbin_
                   FROM dba_segments
                  INNER JOIN
                        dba_recyclebin
                     ON (tablespace_name=ts_name
                         AND segment_name=object_name)
                  WHERE tablespace_name='TEST')
    SELECT      size_, -- tablespace size
         free_, -- free space reported
         used_, -- segment space used
         fbin_, -- segment space in recycle bin
         (size_ - free_ - used_ + fbin_) left_ -- 64K overhead per data file
      FROM      dbf_size, dbf_free, dbf_used, dbf_fbin
    /which does
    SQL> WITH
      2  dbf_size AS (SELECT SUM(bytes) size_
      3                 FROM dba_data_files
      4                WHERE tablespace_name='TEST'),
      5  dbf_free AS (SELECT SUM(bytes) free_
      6                 FROM dba_free_space
      7                WHERE tablespace_name='TEST'),
      8  dbf_used AS (SELECT SUM(bytes) used_
      9                 FROM dba_segments
    10                WHERE tablespace_name='TEST'),
    11  dbf_fbin AS (SELECT SUM(bytes) fbin_
    12                 FROM dba_segments
    13                INNER JOIN
    14                      dba_recyclebin
    15                   ON (tablespace_name=ts_name
    16                       AND segment_name=object_name)
    17                WHERE tablespace_name='TEST')
    18  SELECT     size_,
    19     free_,
    20     used_,
    21     fbin_,
    22     (size_ - free_ - used_ + fbin_) left_
    23    FROM     dbf_size, dbf_free, dbf_used, dbf_fbin
    24  /
         SIZE_      FREE_      USED_      FBIN_      LEFT_
       5242880    5177344    2162688    2162688      65536
    SQL> alter tablespace test add datafile 'C:\ORACLE\ORADATA\XE\TEST2.DBF' size 5m;
    Tablespace altered.
    SQL> WITH
      2  dbf_size AS (SELECT SUM(bytes) size_
      3                 FROM dba_data_files
      4                WHERE tablespace_name='TEST'),
      5  dbf_free AS (SELECT SUM(bytes) free_
      6                 FROM dba_free_space
      7                WHERE tablespace_name='TEST'),
      8  dbf_used AS (SELECT SUM(bytes) used_
      9                 FROM dba_segments
    10                WHERE tablespace_name='TEST'),
    11  dbf_fbin AS (SELECT SUM(bytes) fbin_
    12                 FROM dba_segments
    13                INNER JOIN
    14                      dba_recyclebin
    15                   ON (tablespace_name=ts_name
    16                       AND segment_name=object_name)
    17                WHERE tablespace_name='TEST')
    18  SELECT     size_, -- tablespace size
    19     free_, -- free space reported
    20     used_, -- segment space used
    21     fbin_, -- segment space used in recycle bin
    22     (size_ - free_ - used_ + fbin_) left_
    23    FROM     dbf_size, dbf_free, dbf_used, dbf_fbin
    24  /
         SIZE_      FREE_      USED_      FBIN_      LEFT_
      10485760   10354688    2162688    2162688     131072Message was edited by:
    Hans Forbrich
    Cleaned up the script and tested with second data file added to verify LMT overhead.

  • How to correctly use Hide All/Show All in RH HTML review?

    When using the Hide All or Show All filter options seen in RH HTML's Review Pane it states that all "comments and changes are hidden or seen in Review Pane as well as in Design Editor."  I cannot see any change when I look at the inserted or deleted items in the Design View.  Am I missing something?  I am trying to find a way to show all changes as "final' like Word 2010 does by using "Final" before we accept/reject these changes.  It appears that "View Selected Item" of the active topic may work the same way as I am hoping and shows all changes as if they were already accepted. Am I correct?
    I haven't heard from anyone in the forum so I wonder if I wasn't clear enough?  I am just trying to find out how you can view track changes seen inside a project's topics as if they were accepted, without having actually accepted them yet.  I see that when I select the "View Selected Item" button I see everything, whether it inserted or deleted.  Is that the only way to get a feel of what the final topic would 'look' like?

    Resolved using the Conditions on the workbook.

  • How to correctly use spot colours in Photoshop?

    Hi,
    Using CS2, I've created one of those swooshy Macintosh Panther wallpaper images, with various layers of sweeping lines and tinted gradient arcs.
    Now I want to create the image using just tints of pantone 519 but I'm unsure of how to work with pantone colours in photoshop. I've pulled up the solid coated pantone library and located the swatch, but how do I specify various tints of this colour?
    I've searched the forum and come across spot channels, and have read the photoshop help entry on this, but still can't understand how to do it. From what I've read, I make a selection, then create a spot channel of the colour and set the solidity to 100%. If I want an 80% tint, I just adjust the solidity to 80%. Is this correct, or is the solidity more like transparency than tint?
    In addition, how do I create a gradient between these two colours?
    Final question - I have an element I want to import from Illustrator that uses the same spot colour. Do I have to deal with this any differently to the normal copy and paste as a smart object?
    Sorry, I'm sure this is really quite easy.
    Thanks for any help.
    Steven

    Why not just mode grayscale (or better yet a black and white adjustment layer, then mode grayscale), adjust levels, new spot channel, move dot from gray channel to spot channel? If it was made in RGB 519, your green channel is probably best to make the move to grayscale. If you're working in CMYK, then the magenta channel (unless of course you're using pictures with UCR/GCR).
    <br />
    <br />I guess I don't understand how you can say "I'll set it up best in CMYK" but can't get it to one color.
    <br />
    <br />Here's the tut version using the green channel only. If you do some channel mixing, I'm sure you could get something a little nicer.
    <br />
    <br />
    <a href="http://www.pixentral.com/show.php?picture=1jaDKpRgglatQZJhuknYJ4TLhAUUq1" /></a>
    <img alt="Picture hosted by Pixentral" src="http://www.pixentral.com/hosted/1jaDKpRgglatQZJhuknYJ4TLhAUUq1_thumb.jpg" border="0" />

  • How to correctly use TM

    Hi, I have a few questions about TM.
    1. I've set up TM to back up by mac 250g HD onto a 500G external HD. My understanding was that it would back up the whole HD initially, and then just back up changes made to my iMac after that every hour. After only 3 days, it's telling me that it needs to delete old backups to continue. I've made very few changes to my machine so I don't understand why it could be full if it only backs up the changes. What could be wrong or is this normal?
    2. Secondly, once I've backed up, I'm confused how to view the data. I tried going into iPhoto and Itunes and opening up the apps to see my pictures and songs. I only get a window that says how large the file is. Can we view the data, or is it only there if we need to restore the full libraries? What if I only need a few pictures or songs retrieved? How would I view these items and get them back onto my machine?
    I hope I was clear enough and would appreciate your input. Thanks.

    Matthew Jackson wrote:
    Hi, I have a few questions about TM.
    1. I've set up TM to back up by mac 250g HD onto a 500G external HD. My understanding was that it would back up the whole HD initially, and then just back up changes made to my iMac after that every hour. After only 3 days, it's telling me that it needs to delete old backups to continue. I've made very few changes to my machine so I don't understand why it could be full if it only backs up the changes. What could be wrong or is this normal?
    not really normal give your drive sizes. use TimeTracker to see what exactly TM backs up every time
    http://www.charlessoft.com/
    There are a few things that can cause very large incremental backups. mostly that would be large database files like entourage database or any virtual machine database. do you have any of those?
    2. Secondly, once I've backed up, I'm confused how to view the data. I tried going into iPhoto and Itunes and opening up the apps to see my pictures and songs.
    vast majority of apps including itunes are not integrated with time machine. that means that to restore something you have to do it from finder. in finder go to your music folder->itunes->itunes music and start time machine. locate the song you want to restore and restore it. then double-click it to import it back into itunes.
    if you have ilife 08 or later then iPhoto IS integrated with TM. this means that you can use TM in iphoto interface. when you start TM in iphoto you should see a series of iphoto windows going back in time. you can scroll back and restore what you want. if you have a n earlier version of iphoto then it is not integrated with TM and you have to use TM from finder to restore your iphoto picture.
    I only get a window that says how large the file is.
    I'm not sure what you are talking about. which file?
    Can we view the data, or is it only there if we need to restore the full libraries? What if I only need a few pictures or songs retrieved? How would I view these items and get them back onto my machine?
    I hope I was clear enough and would appreciate your input. Thanks.

  • How to correctly use adfUtils.waitForServer()?

    I used PMD to check OATS automation scripts code. The quick fix automatically added adfUtils.waitForServer() to my scripts. But when i run scripts, it got stuck at this method. Anyone knows what's wrong?
    Example:
    adfUtils.waitForServer();
    web.window("/web:window[@index='0']").navigate(url);
    The time is out before the URL is entered.

    Do only use System Update if you have problems with a driver or Thinkvantage Tool - feature.
    In my company we never used System update and the laptops are running without any changes (except Windows update) since 5 to 6 years. So i have removed TVSU from all computers.
    System Update is a very excellent tool after a clean install from a Windows CD/DVD to install all Lenovo drivers and tools you want to use. A disadvantage of cyclic updates via System Update is, that parts of old drivers in most cases will be kept because the newer driver will be installed over the old one in most cases, which leads after several updates to an instability of the system.
    Just my private opinion...
    My home-forum: http://www.thinkpad-forum.de
    Wiki: Deutsches ThinkPad-Wiki English ThinkWiki
    My ThinkPad-Collection

  • How to correctly use force?

    i have this type

    Hi,
    Your code (with a / after the second CREATE TYPE command) works fine for me.
    Whenever you have a problem, post a complete test script that anyone can run to re-create the problem.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002
    What do you mean be "not working"?  If you're getting an error message, why not post it?
    How do you know that FORCE causes the problem?  Does the second CREATE TYPE statement work for you if you remove FORCE?

  • How to correctly use the evaluate() method in Xpath?

    I have this sample code. I would expect the output to be something like
    Channel #0
    Channel Name : Ch1
    Channel #1
    Channel Name : Ch2
    Channel #2
    Channel Name : Ch3
    but all I get is
    Channel #0
    Channel Name : Ch1
    Channel #1
    Channel Name : Ch1
    Channel #2
    Channel Name : Ch1
    Do I misuse the evaluate() method? It seems the evaluate method disregards the"doc" start node I pass in and always start from the beginning of the XML...
    Very appreciate your suggestion. Thank you very much.
    import javax.xml.xpath.*;
    import org.xml.sax.InputSource;
    import java.io.StringReader;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    public class EvaluateTest {
         * @param args
         public static void main(String[] args) {
              String myxml = "<?xml version='1.0' encoding='utf-8' ?><mytest><ChannelList>" +
              "<Channel><ChannelId>0001</ChannelId><ChannelName>Ch1</ChannelName></Channel>" +
              "<Channel><ChannelId>0002</ChannelId><ChannelName>Ch2</ChannelName></Channel>" +
              "<Channel><ChannelId>0003</ChannelId><ChannelName>Ch3</ChannelName></Channel>" +
              "</ChannelList></mytest>";
              //Get the Document object
              Document doc = null;
              try {
                   InputSource inputSource = new InputSource();
                   inputSource.setCharacterStream( new StringReader(myxml));
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder db = factory.newDocumentBuilder();
                   doc = db.parse(inputSource);
                   //Iterate thru the Channel list
                   NodeList channellist = getSubElements(doc, "/mytest/ChannelList/Channel");
                   if (channellist==null)
                        System.out.println("the channel list is null");
                   for (int i=0, len=channellist.getLength(); i<len; i++) {
                        System.out.println("Channel #" + i);
                        /*{XPathFactory factory = XPathFactory.newInstance();
                        XPath anxpath = factory.newXPath();
                        String result = (String)anxpath.evaluate(".", channellist.item(i), XPathConstants.STRING);
                        out.println(result);}*/
                        String name = getTagValue(channellist.item(i), "//ChannelName/text()", -1);
                        System.out.println("Channel Name : " + name);
              catch ( Exception e ) {
                   e.printStackTrace();
                   return;
         //Get the text value of a tag from a document object using XPath method
         static public String getTagValue(Object doc, String xpathstr, int index) throws Exception {
              String result = "";
              if ((doc==null)     || (xpathstr==null) || "".equals(xpathstr))
                   return result;
              XPathFactory factory = XPathFactory.newInstance();
              XPath xpath = factory.newXPath();
              result = (String)xpath.evaluate(xpathstr, doc, XPathConstants.STRING);
              if (result==null)
                   result = "";
              return result;
         static public NodeList getSubElements(Object doc, String xpathstr) throws Exception {
              if ((doc==null)     || (xpathstr==null) || "".equals(xpathstr))
                   return null;
              XPathFactory factory = XPathFactory.newInstance();
              XPath xpath = factory.newXPath();
              Object result = xpath.evaluate(xpathstr, doc, XPathConstants.NODESET);
              return (NodeList)result;
    }

    Sorry here is a repost of the code. Didn't realize there is a code tag feature.
    import javax.xml.xpath.*;
    import org.xml.sax.InputSource;
    import java.io.StringReader;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    public class EvaluateTest {
        * @param args
       public static void main(String[] args) {
          String myxml = "<?xml version='1.0' encoding='utf-8' ?><mytest><ChannelList>" +
                      "<Channel><ChannelId>0001</ChannelId><ChannelName>Ch1</ChannelName></Channel>" +
                                 "<Channel><ChannelId>0002</ChannelId><ChannelName>Ch2</ChannelName></Channel>" +
                      "<Channel><ChannelId>0003</ChannelId><ChannelName>Ch3</ChannelName></Channel>" +
                      "</ChannelList></mytest>";
          //Get the Document object
          Document doc = null;
          try {
                InputSource inputSource = new InputSource();
                inputSource.setCharacterStream( new StringReader(myxml));
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = factory.newDocumentBuilder();
                doc = db.parse(inputSource);
                //Iterate thru the Channel list
                NodeList channellist = getSubElements(doc, "/mytest/ChannelList/Channel");
                if (channellist==null)
                      System.out.println("the channel list is null");
                for (int i=0, len=channellist.getLength(); i<len; i++) {
                      System.out.println("Channel #" + i);
                      String name = getTagValue(channellist.item(i), "//ChannelName/text()", -1);
                      System.out.println("Channel Name : " + name);
          } catch ( Exception e ) {
                e.printStackTrace();
                return;
       //Get the text value of a tag from a document object using XPath method
       static public String getTagValue(Object doc, String xpathstr, int index) throws Exception {
          String result = "";
          if ((doc==null)     || (xpathstr==null) || "".equals(xpathstr))
                return result;
          XPathFactory factory = XPathFactory.newInstance();
          XPath xpath = factory.newXPath();
          result = (String)xpath.evaluate(xpathstr, doc, XPathConstants.STRING);
          if (result==null)
                result = "";
          return result;
       static public NodeList getSubElements(Object doc, String xpathstr) throws Exception {
          if ((doc==null)     || (xpathstr==null) || "".equals(xpathstr))
                return null;
          XPathFactory factory = XPathFactory.newInstance();
          XPath xpath = factory.newXPath();
          Object result = xpath.evaluate(xpathstr, doc, XPathConstants.NODESET);
          return (NodeList)result;
    }

  • Which structure to use for time-restricted thread pools

    Hi,
    I am looking for the advice on the best concurrent structure (if such even exist)
    for executing concurrent jobs and forcing the timeout on these.
    Here is the problem description:
    I have to call up to 50 webs services.
    I want to run these web service calls concurrently (i.e. in separate threads)
    I want to force timeout, or execution windows of each one of these threads.
    E.g. I want to make sure that each threads completes the execution in 5 sec
    regardless if the web service result has returned or not.
    Is there a combination of the pool and a worker type from java.util.concurrent
    or elsewhere that would allow me to implement this functionality.
    Thank you in advance,
    Edmon

    Do you want get rich easily?
    You can change life, you can have money as much as you want. All you have to do is to send 12 dollars to 6 people bank accounts.
    All you have to do is the fallowing:
    You have to have bank account. You have to send 2 $ to below listed bank accounts. This is legal, you made a favour for those people and for your self.
    This is the bank accounts:
    1. LT957300010074515201
    2. LT217044000017612013
    3. LT547400012388523830
    4. LT857044000879616105
    5. LT577300010085485906
    6. LT837300010088377105
    After sending money, you need to delete the first bank account and make room for your account, after deleting first account, in the bottom of the list write your accounts number. You have to delete only the first one. Very important to do it honestly.

Maybe you are looking for