Waiting the main thread till all child thread has completed

I am in the process of developing a batch application in Java 5.0 which extensively uses the java.util.concurrency API. Here is a small description of what the batch process will do,
1. Retrieve values from DB and populate a blocking queue in main thread.
2. Instantiate a Threadpool by calling, Executors.newFixedThreadPool(2)
3. Invoking the following block of code from the main thread,
while(!iBlockingQueue.isEmpty()) {
    AbstractProcessor lProcessor = new  DefaultProcessor((BusinessObject)iBlockingQueue.remove());
    iThreadPool.execute(lProcessor);
}DefaultProcessor is a class that extends Thread.
4. Invoking the following block of code from the main thread,
iThreadPool.shutdown();
try {
     iThreadPool.awaitTermination(30, TimeUnit.SECONDS);
     } catch (InterruptedException interruptedException) {
          iLogger.debug("Error in await termination...", interruptedException);
Since, this is the first time I am using the java.util.concurrency API, I want to know whether this is the right way to wait for all the child threads to complete before executing further statements in the main (parent) thread. Or do I necessariliy have to call join() to ensure that the main thread waits for all the child threads to finish which can only happen when the queue is empty.
Please note here that as per the requirements of the application the blocking queue is filled only once at the very beginning.
I will appreciate any inputs on this.
Thanks.

looks like you would be waiting on a queue twice, once in the loop and again, under the hood, in the threadpool's execute()
the threadpool's internal queue is all that is needed
if your iBlockingQueue is also the threadpool's internal queue, you might have a problem when you remove() the BusinessObject
by making DefaultProcessor extend Thread you are, in effect, implementing your own threadpool without the pooling
DefaultProcessor need only implement Runnable, it will be wrapped in a thread within the pool and start() called
to implement a clean shutdown, I suggest writing DefaultProcessor.run() as an infinite loop around the blocking queue poll(timeout) and a stop flag that is checked before going back to poll
class DefaultProcessor implements Runnable {
  private BlockingQueue myQ;
  private boolean myStopFlag;
  DefaultProcessor( BlockingQueue bq ) { myQ = bq; }
  public void run() {
    BusinessObject bo = null;
    while( !myStopFlag && (bo=myQ.poll( 10, SECONDS )) ) {
      // business code here
  public void stop() { myStopFlag = true; }
} Now, after iThreadPool.shutdown(), either call stop() on all DefaultProcessors (or alternatively send "poison" messages to the queue), and give yourself enough time to allow processing to finish.

Similar Messages

  • Closing all child threads when closing the stage

    I have multiple instances of child threads which are started and should continue to execute in till the applications exits.
    I have classes which extends Task and I create the threads as
    new Thread(object of the class).start();
    when it comes to interrupting/stoping (dont know which one is correct, please let me know) the threads which should be done inside
    primaryStage.onCloseOperation(){}
    here i want to end all child threads but since my threads are spreaded across different classes, my not having a clear picture how to achieve this.
    I know there is some designing problem, in my application, when it comes to threads, but I am not able to figure out how to resolve out.

    Use thread.setDaemon(true) Thread (Java Platform SE 7 )
    I suggest to use the Executor Framework and a ThreadFactory, to only need to create a daemon thread once.
    Something like this:
    Executor executor = Executors.newCachedThreadPool(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setDaemon(true);
                    return thread;
    And then use it like this:
    executor.execute(yourTaskOrRunnable);
    When there are only daemon threads running, the JVM will halt and also stop all daemon threads.

  • How do I add the rotate button to the main toolbar for all users

    How do I add the rotate button to the main toolbar for all users. I have a Windows 2003 Citrix farm with Adobe Reader 8. I can add it user by user but I want to add it to all users at once. All users need this rotate button,
    Thanks in advance
    ND

    Try the Reader forum. I have no clue.

  • I have Thunderbird 24.5.0. When I double click the desktop item to open it up, it opens immediately, but when I'm in the main page with all the folders on the

    I have Thunderbird 24.5.0. When I double click the desktop item to open it up, it opens immediately, but when I'm in the main page with all the folders on the left & the corresponding email details on the right of that same page, it seems to have problems. Before, when I would highlight a certain box / folder (whether it would b “inbox”, “sent” folder, “trash” folder, or whatever, it takes a good 5 min (minimum) to open that certain folder so I can see the emails of that folder.
    Can u help me determine what is causing this? Just 3 days ago, it was fine.
    Thank you

    What is your anti-virus software?

  • My Iphone 4, to which all my outlook email is forwarded to. is only receivng some of the emails but not all. It has worked beautifully in the past but no longer. What can I do to get all emails?

    My Iphone 4, to which all my outlook email is forwarded to. is only receivng some of the emails but not all. It has worked beautifully in the past but no longer. What can I do to get all emails?

    I would just explain that this just started happening, that nothing has changed on the phone, that it is an original iPhone and I wondered if they are implementing a change in coverage with their Edge network in my area.
    If you restore your phone, you will be given an option to back up your phone at the beginning of the process (see step 6 here: http://support.apple.com/kb/HT1414).  You will be given the option to restore to that backup at the end of the restore process.  Your messages are stored in the backup so restoring to the backup will return the messages to your phone.  Be sure to import your photos and videos to your computer (see http://support.apple.com/kb/HT4083) and back up your contacts somewhere before restoring your phone as these sometimesget lost in the restore process.

  • HT204291 the airplay icon on all my devices has a lock on it.  I don't know how to unlock it to get it to work with my Apple TV

    The Airplay icon on all my devices has a lock on it.  How do I unlock it to share with my Apple TV.  I have homeshare on everything and I simply can't figure this out.

    The Best Alternatives for Security Questions and Rescue Mail
         1.  Send Apple an email request at: Apple - Support - iTunes Store - Contact Us.
         2.  Call Apple Support in your country: Customer Service: Contact Apple support.
         3.  Rescue email address and how to reset Apple ID security questions.
    An alternative to using the security questions is to use 2-step verification:
    Two-step verification FAQ Get answers to frequently asked questions about two-step verification for Apple ID.

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Is it possible to get the main class name in a Thread context ?

    for example, i want to get the main class name (the first entry of the program).
    public class Test implements Runnable {
         public Test() {}
         public static void main(String[] args) {
              new Thread(new Test()).start();
         public void run() {
              try {
                   //Want to get the main class name (not the current class name)
                   throw new Throwable();
              } catch (Throwable e) {
                   e.printStackTrace();
    }

    Acutally, i wanna make clear about the concept of a "Thread"
    Is it true that ..
    the main() method is a thread , once I create another thread in the program , both of (or all of them) will contains it owns stack exception information ?
    My english is poor, please try to understand it. Thx

  • Can a parent thread kill a child thread?

    I'm writing a multi-threaded application in which it is possible for one of the threads to go into an infinite loop. Is there any way for a parent thread to actually kill the child thread that has gone into the infinite loop? Of course the parent thread won't actually be able to discern whether or not the child thread is in an infinite loop. I would specify some time out value, and when it has been exceeded, then I would want to kill the child thread. Is this possible without setting any sort of flag that the child would read, because once it gets stuck inside an infinite loop, there will be no way to read the flag.

    Here's an example of a program that I wrote to simply ping a server. It works somewhat backwards from what you were looking for (the child interrupts the parent) but should provide some clue:
    import java.net.*;
    import java.io.*;
    import java.util.Date;
    public class ServerPing extends Thread {
      String [] args;
      public static void main(String[] args) throws Exception {
        ServerPing sp = new ServerPing(args);
        sp.start();
      ServerPing(String [] args) {
        this.args = args;
      public void run() {
        Pinger pinger = new Pinger(this);
        pinger.start();
        try {
          sleep(30000);
        catch (InterruptedException x) {
          System.exit(0); // this is ok. It means the pinger interrupted.
        System.out.println("TIMEOUT");
        System.exit(1);
    class Pinger extends Thread {
      Thread p = null;
      Pinger (Thread p) {
        this.p = p;
      public void run() {
        try {
          URL simpleURL = new URL("http://localhost:7001/ping.jsp");
          BufferedReader in = new BufferedReader(new InputStreamReader(simpleURL.openStream()));
          String inputLine;
          while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
          in.close();
          p.interrupt();   // <<-- interrupt the parent
        catch (Exception x) {
          x.printStackTrace();
    }

  • Need to delete data from main table and all child tables ...

    hi all,
    i need to delete rows pertaining to perticular table and all the child
    tables basing on certain code.i need to write a procedure to which i will
    pass the table name and code..
    like del_info(tab_name,code)
    example:
    suppose if i call as del_info(clients,760)
    the procedure should delete all info reg. code 760
    and the table clients and also all the child records of this table
    perting to code 760.
    simply .. i need to delete from the table passed and also
    all the child tables down the heirarchy regarding certain code ...
    help ???
    Ravi Kumar M

    Hi,
    Depends how you defined referential integrity.
    You can use ON DELETE CASCADE, please read the next doc http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/clauses3a.htm#1002692
    Hope this help you,
    Nicolas.

  • My newest Apple TV work load the main page.  All I get is a page saying home sharing and settings. Even when I restart, restore, it goes back to this page.  It worked once since buying it then suddenly it stopped and I keep getting this page as the main p

    Hi,
    My newest Apple TV which I bought on Amazon finally arrived and worked for 2 days.  Now all of a suudden it is refusing to load the main page to select movies, radio, netflix etc.  All I am getting is a page saying homesharing with only an option to select Computers of Settings.  I have reset the Apple TV, restored it but nothing...it keeps going back to this page saying computers and settings.  I've tried updating the software as well but after 30 minutes or so it tells me software update was unsuccessful and to go to settingsand choose restore and the loop begins?  Is it permanently broken?

    I had the same issue Berry.  What worked for me was going to the General Settings and doing a reset from there.  I got all my apps back but had to re-enter all my information for iTunes, Netflix, Hulu etc...
    Hope it works for you too!

  • Main Server crashed. Currently using AD that exist in a desktop computer with Sever 2008 R2 Standard installed. Need to copy the AD to the main server. All in same IP range.

    Hi Guys,
    Unfortunately the main server crashed and I have re-installed Server 2008 R2 Standard in it. The server had only ADDS, DNS Services and File Services. I have the AD on a desktop computer where Server 2008 R2 Standard is installed. All the user computers
    and the servers are in same IP range. I tried replication but an error pops up saying "you will not be able to install a writable replica domain controller at this time because the RID master DC-TURBO.turbo.com is offline"
    CAN ANYONE HELP ME TO FIX THIS ISSUE OR IS THERE ANY WAYS TO MAKE MY MAIN SERVER UP.!!!
    HELP ME PLEASE

    Hi Guys,
    Unfortunately the main server crashed and I have re-installed Server 2008 R2 Standard in it. The server had only ADDS, DNS Services and File Services. I have the AD on a
    desktop computer where Server 2008 R2 Standard is installed. All the user computers and the servers are in same IP range. I tried replication but an error pops up saying "you will not be able to install a writable replica domain controller
    at this time because the RID master DC-TURBO.turbo.com is offline"
    Assuming that you have an additional domain controller on your desktop computer, you will need too SEIZE the FSMO roles to your desktop computer. Then re-install the OS on the old DC and do a Metadata cleanup and then go with promoting
    the additional domain controller. These are the tasks which you need to do:
    Seize the FSMO roles from your crashed old DC to your desktop computer. Using Ntdsutil.exe to transfer or seize FSMO roles to a domain controller
    Do a Metadata cleanup and remove old objects related to your crashed DC.  Clean Up Server Metadata
    Re-install OS on your OLD Sever and promote it as additional domain controller to your desktop computer(DC).
    Transfer the FSMO roles back to your server which is a clean DC now. How to view and transfer FSMO roles in the graphical user interface
    Mahdi Tehrani   |  
      |  
    www.mahditehrani.ir
    Please click on Propose As Answer or
    to mark this post as
    and helpful for other people.
    This posting is provided AS-IS with no warranties, and confers no rights.
    How to query members of 'Local Administrators' group in all computers?

  • Killing Parent thread can kill child thread

    hi frnds
    can u help me on thread
    i want to know if i am kill my parent thread.can it automatically kill chhild thread also.
    and i want to know is there any way in java to kill thread
    plz reply

    ajju29 wrote:
    and i want to know is there any way in java to kill threadNo, not safely and not reliably. Since there's no way to "kill" a thread without its cooperation, the previous question is not relevant as well.
    What you want to do is set some flag that your thread periodically checks and maybe send an signal and/or interrupt to tell the thread to check the flag earlier. The thread should then quit on its own.
    Everything else is unfixably broken.

  • Hi my main computer with all my albums has died but on my itunes account ther is only 111 songs how can i transfer the rest from my ipod touch

    hi my main computer has died and i have 1500 songs on my ipod touch but only 111 songs show on my i tunes account is ther a way to sync with a new computer and not lose all my albums

    Recovering your iTunes library from your iPod or iOS device: Apple Support Communities

  • HT1417 why have all my downloaded songs stored in i cloud shown twice on the main music menu all of a sudden? how do i get the space back, without spending hours deleting copies ?

    why are all my download items duplicated in i cloud all of a sudden? how do i get the space back so i can re-synch muy i pod classic without spending hours deleting ?

    Why? A glitch. The second copies are links to your purchases in the cloud and are not taking up any room. Sign out of the store and they should disappear. Sign back in again and they should stay gone.
    tt2

Maybe you are looking for

  • Why do my photos have a green tint when placing them into Muse?

    I am placing photos of portraits into Muse and the colors look terrible. There is a green tint that dulls down the pictures.Top is one of the originals, and bottom is a screenshot in Muse.

  • File name selection

    In filechooser, is there a way that I can "scroll" the displayed list of files based upon each keystroke entered into the dialog's "File Name"?

  • Splite DN with one sales order

    When created D/N ,system gave the message as following, could you please help me to figure out what's the rootcause and how to mkae it to one D/N,thanks very much Item 000020: delivery split due to conflicting header data (AKKUR: 32.90000 <->        

  • Could not make multiple connection with bluetooth.

    Hi all, I am sorry if i have posted this topic in wrong forum. I was trying to create a scenario like this A PC running as a server with bluetooth dongle attached. Mobile A connects to this PC and two text fields and a button is showed on Mobile A. W

  • What is the best easy setup for d600 nikon. and what is the best export for hd movie, 11 min ?

    i'm exporting my movie in mpeg4, 1960X1080, for streaming. all the movie is going well, but there is some cubes in the sky, and also, some frames jumpes. I treid few times, but its always the same. Thank you,Lena