Waiting for a thread to finish

I've been researching this issue for a couple of days, but I dont think I know enough about threading to ask the right question in a search engine. Sorry if this is a basic blunder....I dont write swing often and it shows.
I have a swing app that includes a long task so I have implemented a progress bar. I need to wait until the progress bar task completes before continuing to the rest of the method. I've tried:
1. Putting the progress bar within a while loop (while task not complete...) but the progress bar dialog does not render fully. I've even added repaint, but still the dialog looks blank.
2. SwingUtilities.invokeLater, but it doesnt wait until the progress bar is finished
3. SwingUtilities.invokeAndWait, though after all the reading I did about deadlock conditions I didnt like the idea. However I was desperate so I tried it and got an error:"Cannot call invokeAndWait from the event dispatcher thread".
4. Putting the code that needs to occur after the progress bar in an "invokeLater" thread
5. I've also used the ProgressBarDemo from the java.sun example with the swingworker hoping the worker thread would handle the issue.
A much smaller version of the code is below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class ProblemCode extends JFrame
     private JFrame jFrame = null;
     private JPanel jMain = null;
     private JButton startButton = null;
     public ProblemCode()
          initialize();
     public void initialize()
          //Setup the main application window size
          jFrame = new JFrame();
          jFrame.setContentPane(getJMainPanel());
          jFrame.pack();
          jFrame.addWindowListener(new java.awt.event.WindowAdapter()
               public void windowClosing(java.awt.event.WindowEvent e)
                    dispose();
          SwingUtilities.invokeLater(new Runnable()
            public void run()
                jFrame.setVisible(true);
     private JPanel getJMainPanel()
          if(jMain == null)
               jMain = new JPanel();
               jMain.add(getJStartButton());
          return jMain;
     private JButton getJStartButton()
          if (startButton == null)
               startButton = new JButton();
               startButton.setText("Start");
               startButton.setVisible(true);
               startButton.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                       SwingUtilities.invokeLater(new Runnable()
                             public void run()
                                      progBar();
                        System.out.println("Do this after the progress bar completes");
                        SwingUtilities.invokeLater(new Runnable()
                             public void run()
                                  System.out.println("invokeLater doesnt work either....");
          return startButton;
     private void progBar()
        JFrame jProgFrame = new JFrame("JProgressBar Sample");
        jProgFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = jProgFrame.getContentPane();
        final JProgressBar progressBar = new JProgressBar();
        new Thread()
            private int counter = 0;
            private final int val = (int)(Math.random()*10)+1;
            public void run()
                for(int i = 0;i <= 100;i++)
                    counter += val;
                    javax.swing.SwingUtilities.invokeLater( new Runnable()
                        public void run()
                            progressBar.setValue(counter);
                    try
                        Thread.sleep(500);
                    catch (InterruptedException e)
        }.start();
        progressBar.setStringPainted(true);
        Border border = BorderFactory.createTitledBorder("Reading...");
        progressBar.setBorder(border);
        content.add(progressBar, BorderLayout.NORTH);
        jProgFrame.setSize(300, 100);
        jProgFrame.setVisible(true);
     public static void main(String[] args)
          SwingUtilities.invokeLater(new Runnable()
               public void run()
                    new ProblemCode();
}Thank you for taking the time to review this.

Hi,
I made some tiny changes in yoyr code, marked with
// PBHere the changed code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class ProblemCode extends JFrame {
    private JFrame jFrame = null;
    private JPanel jMain = null;
    private JButton startButton = null;
    public ProblemCode() {
     initialize();
    public void initialize() {
     // Setup the main application window size
     jFrame = new JFrame();
     jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // PB
     jFrame.setContentPane(getJMainPanel());
     jFrame.pack();
     jFrame.addWindowListener(new java.awt.event.WindowAdapter() {
         public void windowClosing(java.awt.event.WindowEvent e) {
          dispose();
     SwingUtilities.invokeLater(new Runnable() {
         public void run() {
          jFrame.setVisible(true);
    private JPanel getJMainPanel() {
     if (jMain == null) {
         jMain = new JPanel();
         jMain.add(getJStartButton());
     return jMain;
    private JButton getJStartButton() {
     if (startButton == null) {
         startButton = new JButton();
         startButton.setText("Start");
         startButton.setVisible(true);
         startButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                   progBar();
              System.out
                   .println("Do this after the progress bar completes");
              SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                   System.out
                        .println("invokeLater doesnt work either....");
     return startButton;
    private void progBar() {
     JFrame jProgFrame = new JFrame("JProgressBar Sample");
     jProgFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     Container content = jProgFrame.getContentPane();
     final int val = (int) (Math.random() * 10) + 1; // PB
     final JProgressBar progressBar = new JProgressBar(0, 100 * val); // PB
     progressBar.setStringPainted(true);
     Border border = BorderFactory.createTitledBorder("Reading...");
     progressBar.setBorder(border);
     content.add(progressBar, BorderLayout.NORTH);
     jProgFrame.setSize(300, 100);
     jProgFrame.setVisible(true);
     // PB
     final Thread longTask = new Thread() {
         private int counter = 0;
         public void run() {
          for (int i = 0; i <= 100; i++) {
              counter += val;
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                   progressBar.setValue(counter);
              try {
               Thread.sleep(100); // PB
              } catch (InterruptedException e) {
     longTask.start();
     // PB
     Thread followUpTask = new Thread(new Runnable() {
         @Override
         public void run() {
          try {
              System.out.println("Follow up task is waiting");
              longTask.join();
              System.out.println("Follow up task  continues");
          } catch (InterruptedException e) {
              e.printStackTrace();
     followUpTask.start();
    public static void main(String[] args) {
     SwingUtilities.invokeLater(new Runnable() {
         public void run() {
          new ProblemCode();
}Piet

Similar Messages

  • Application waits for the thread to finish

    Hi all,
    I have a class let say test that extends Thread.
    In my application i say:
    test Xtest = new test();
    Xtest.start();
    System.out.println("Thread finished");
    I need my application to wait for the thread to finish for it to continue, i.e. in my example print "Thread finished" .
    Can someone help me.
    Thanks in advance for your help.
    Best regards,
    Saadi MONLA

    This should work:
    test Xtest = new test();
    Xtest.start();
    Xtest.join();
    System.out.println("Thread finished");

  • Waiting for a thread to die.

    Hello, I hope you can help me...
    I am writting a jdk1.4.1 Swing application that displays a small animation. This animation is processed from within a separate thread. My program makes a call starting this 'animation thread'. For practical reasons my program needs to wait for this thread to die (and thus the full animation to be shown) before it can continue. I am waiting for the animation thread to die using Threads 'join' method. However the problem with this is that I am forcing the GUI thread to wait resulting in the animation being calculated but not displayed. And so... how can I fix this... all I want is to wait until the animation is shown.
    What I would like to do is:
    1. Start animation;
    2. wait intil animation has completed;
    3. continue with program.
    Any help or advice will be greatly appreciated.
    Thank you in advance.

    Maybe this design could work for you. You divide your program into three parts running in three separate threads.
    1. The main thread handling GUI stuff and coordination of the two other threads.
    2. A working thread doing most of what the main thread is now doing.
    3. The animation thread.
    With this division of labour the working thread is waiting for the animation thread to finish (the main GUI thread isn't). The main thread will be free at all times to react to the users input or updating the screen or whatever, while the other two threads are cooperating to produce the animation.

  • When server start, get "Waiting for another script to finish..." message and doesn't go anywhere.

    Hello, my engineer (Japanese) is trying to start AdobeMediaServer but he got stuck after getting "Waiting for another script to finish..." message. Any idea how to resolve this situation?
    [root@NA1SIBZDH02 /opt/adobe/ams]# ./server start
    NPTL 2.5
    chmod: changing permissions of `./tmp/': 読み込み専用ファイルシステムです
    Waiting for another script to finish...
    [root@NA1SIBZDH02 /opt/adobe/ams]#
    [root@NA1SIBZDH02 /opt/adobe/ams]#
    [root@NA1SIBZDH02 /opt/adobe/ams]# ls -l
    合計 52324
    drwxr-xr-x 15 ams  ams      4096  9月 11 17:54 Apache2.2
    -rwxr-xr-x  1 root root  1061035  9月 11 17:54 License.htm
    -rwxr-xr-x  1 root root    43374  9月 11 17:54 License.txt
    -rwxr-xr-x  1 root root    58827  9月 11 17:54 ReleaseNotes.htm
    -rwxr-xr-x  1 root root     5715  9月 11 17:54 adminserver
    -rwxr-xr-x  1 root root      871  9月 11 17:54 adobe-lq.png
    -rwxr-xr-x  1 root root     2912  9月 11 17:54 ams_icon.png
    -rwxr-xr-x  1 root root  3220552  9月 11 17:54 amsadmin
    -rw-r--r--  1 root root        6  9月 11 17:54 amsadmin.pid
    -rwxr-xr-x  1 root root 11187664  9月 11 17:54 amscore
    -rwxr-xr-x  1 root root  4331472  9月 11 17:54 amsedge
    -rwxr-xr-x  1 root root  3070840  9月 11 17:54 amsmaster
    -rw-r--r--  1 root root        6  9月 11 17:54 amsmaster.pid
    -rwxr-xr-x  1 root root     5242  9月 11 17:54 amsmgr
    drwxrwxrwx  6 ams  ams      4096  9月 11 17:54 applications
    -rwxr-xr-x  1 root root      960  9月 11 17:54 cleanup
    drwxr-x---  3 ams  ams      4096  9月 11 17:54 conf
    drwxr-xr-x  5 ams  ams      4096  9月 11 17:54 creds
    drwxr-xr-x  3 root root     4096  9月 11 17:54 documentation
    -rwxr-xr-x  1 root root 16368842  9月 11 17:54 libadbe_dme.so
    -rwxr-xr-x  1 root root   336065  9月 11 17:54 libadbe_flv.so
    -rwxr-xr-x  1 root root    59248  9月 11 17:54 libasneu.so.1
    -rwxr-xr-x  1 root root    71263  9月 11 17:54 libcares.so
    -rwxr-xr-x  1 root root    71263  9月 11 17:54 libcares.so.2
    -rwxr-xr-x  1 root root    71263  9月 11 17:54 libcares.so.2.0.0
    -rwxr-xr-x  1 root root  1968482  9月 11 17:54 libcrypto.so.1.0.0
    -rwxr-xr-x  1 root root   162403  9月 11 17:54 libexpat.so.1
    -rwxr-xr-x  1 root root  3497472  9月 11 17:54 libfmsccme.so
    -rwxr-xr-x  1 root root  6992879  9月 11 17:54 libhds.so
    -rwxr-xr-x  1 root root   403767  9月 11 17:54 libssl.so.1.0.0
    drwxr-xr-x  2 root root     4096  9月 11 17:54 licenses
    drwxrwxrwx  2 root root     4096  9月 11 17:54 logs
    drwxr-xr-x  5 root root     4096  9月 11 17:54 modules
    drwxr-xr-x  6 root root     4096  9月 11 17:54 samples
    drwxr-xr-x  3 root root     4096  9月 11 17:54 scriptlib
    -rwxr-xr-x  1 root root     7494  9月 11 17:54 server
    -rwxr-xr-x  1 root root   300864  9月 11 17:54 shmrd
    -rwxr-xr-x  1 root root    36206  9月 11 17:54 tcSrvMsg
    drwxrwxrwx  2 root root     4096  9月 11 17:54 tmp
    drwxr-xr-x  9 root root     4096  9月 11 17:54 tools
    -rwxr-xr-x  1 root root     2411  9月 11 17:54 uninstallAMS
    drwxr-xr-x  8 ams  ams      4096  9月 11 17:54 webroot
    [root@NA1SIBZDH02 /opt/adobe/ams]#
    [root@NA1SIBZDH02 /opt/adobe/ams]#
    ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

    A possible cause is security software (firewall) that blocks or restricts Firefox or the plugin-container process without informing you, possibly after detecting changes (update) to the Firefox program.<br />
    Remove all rules for Firefox from the permissions list in the firewall and let your firewall ask again for permission to get full unrestricted access to internet for Firefox and the plugin-container process and the updater process.
    See:
    * https://support.mozilla.com/kb/Server+not+found
    * https://support.mozilla.com/kb/Firewalls

  • Waiting for another script to finish...

    I can no more start or stop FMS3 server, it says :
    Waiting for another script to finish...
    According to the start script, i check
    /home/fms/tmp/script.lck and i have this file as empty, what should
    i do then ?
    Do you all have this file ? /home/fms/tmp/script.lck ?
    Jerome

    My reply is late i just read your problem after having the same, it locked up my whole Ubuntu system.
    Its easy to solve just delete the lock folder you see. Server should restart and work fine.

  • Compressor 4.1.3 hangs Waiting for Create Disc to Finish

    Compressor 4.1.3 hangs at the "Waiting for Create Disc to Finish" stage.  The audio and video streams have been created and are in Finder. The correct drive has been selected in the Actions section and there is a disk in the drive. I have run Compressor Repair.  However there is no activity at the drive (which otherwise works fine and will burn a disk from Finder).  Anyone any ideas?

    I'e not run into this before. Try a different clip – preferably a QuickTime movie. Bring that into Compressor and mark a short section with in and out points. Choose Hard Drive for Output Device in the Job Action section. What happens after you submit it?
    Russ

  • Waiting for many threads

    Hey guys,
    I know how to make one thread wait for another named thread to complete, but how do u make a thread wait for many threads to complete with the added problem of not knowing the names of the threads your waiting for? Looked and been trying for ages but can't get anything to work.
    Thanx
    Lisa

    No i saw it, pehaps i should rephrase with a question, how would you go about giving all these threads a reference? If it ain't obvious already am not great with java and if someone could tell me how to give the threads spawned references it would be great.
    As ive explained the code is really long so am not going to waist peoples time by posting it. Here is basically how i am spawning the threads "willy-nilly" style.
         while ((p < searchTerms.size())&&(p < 30)){
             term = (searchTerms.elementAt(p)).toString();
             NetChecker nc = new NetChecker(term,excludedAdds,refWeb);
             searchClasses.addElement(nc);     
             new Thread(nc).start();
             p++;
         } the classes all return web addresses in a vector, thats why i need all the threads to complete so i can collect all the results
    Thanx
    Lisa

  • DBMS_SCHEDULER wait for job/program to finish

    Hello All,
    I've run into a little limitation on my understanding of DBMS_SCHEDULER.
    I have an executable script which does a network scan. My goal is to lauch this from an application, and wait (could be 5 minutes or 2 hours) for the scan to finish before I return the results.
    Where I'm a little confused, is the flow of the entire process works when I want to wait for the program to complete:
    1 - Define a program?
    2 - Apply arguments?
    3 - Apply credentials
    4 - Define a chain?
    Literally, I'm not sure how to tackle this task. I simply wish to launch to job and wait for it to finish before I go retreive the file from the server. This is what I have so far, just bits and pieces.
    Mayeb I simply missed somethign in the docs, and I'm overcomplicate things.
    Thanks in advance to the community for you assistance.
    Jan S.
    BEGIN
      dbms_scheduler.create_program(
        program_name   => 'network_scan',
        program_type   => 'executable',
        number_of_arguments => 5,
        program_action => 'scan_network.py',
        enabled        =>  FALSE);
      dbms_scheduler.define_program_argument('network_scan',1,'x01=1');
      dbms_scheduler.define_program_argument('network_scan',2,'x02=192.168.1.1');
      dbms_scheduler.define_program_argument('network_scan',3,'x03=24');
      dbms_scheduler.define_program_argument('network_scan',4,'x04=D');
      dbms_scheduler.define_program_argument('network_scan',5,'x05=1521-1523,7777'); 
      vJobName := dbms_scheduler.generate_job_name('NET_SCAN_');
      dbms_scheduler.create_job(job_name => vJobName,
                                  job_type => 'EXECUTABLE',
                                  job_action => '/usr/bin/scan_nework.sh',
                                  number_of_arguments => 5,
                                  enabled => FALSE,
                                  auto_drop => FALSE,
                                  comments => 'Network');
    dbms_scheduler.set_attribute(vJobName,'credential_name', 'SUCREDENTIALS');
      dbms_scheduler.run_job(vJobName,FALSE);
      dbms_scheduler.create_chain (
       chain_name            =>  'net_scan_chain',
       rule_set_name         =>  NULL,
       evaluation_interval   =>  NULL,
       comments              =>  NULL);
      dbms_scheduler.define_chain_step('net_scan_chain', 'step1', 'network_scan');
      SELECT additional_info, external_log_id
      INTO   l_additional_info, l_external_log_id
      FROM   (SELECT log_id,
                     additional_info,
                     REGEXP_SUBSTR(additional_info,'job[_0-9]*') AS external_log_id
              FROM   dba_scheduler_job_run_details
              WHERE  job_name = vJobName
              ORDER BY log_id DESC)
      WHERE  ROWNUM = 1;
      DBMS_OUTPUT.put_line('ADDITIONAL_INFO: ' || l_additional_info);
      DBMS_OUTPUT.put_line('EXTERNAL_LOG_ID: ' || l_external_log_id); 
      -- Wait at least 3 second because its distributed
      dbms_lock.sleep(3);
      SELECT job_name, status, error#, additional_info
      FROM dba_scheduler_job_run_details
      WHERE job_name= vJobName;
      dbms_lob.createtemporary(l_clob, FALSE);
      dbms_scheduler.get_file(
        source_file     => l_external_log_id ||'_stdout',
        credential_name => 'ORACLECREDENTIALS',
        file_contents   => l_clob,
        source_host     => NULL);
      DBMS_OUTPUT.put_line('stdout:');
      DBMS_OUTPUT.put_line(l_clob);
    k Scan');

    See Tom's last reply in this AskTom thread. It shows how to use the DBMS_ALERT package to signal you.
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5320945700346034393

  • [Solved] systemd does not wait for the unit to finish

    My problem is described in the title. I have made a test by enabling the following unit:
    [Unit]
    Description=/etc/rc.local Compatibility
    [Service]
    Type=forking
    ExecStart=/bin/sleep 1000
    TimeoutSec=0
    RemainAfterExit=yes
    After=network.target
    [Install]
    WantedBy=multi-user.target
    The unit is well started (a process sleep 1000 exists). But with a type=forking, systemd is supposed to hang in this case. Instead, the graphical.target is launched, systemctl list-units mention it as dead, but the display manager is started before the sleep 1000 completes. Ho can I force systemd to wait?
    Last edited by olive (2015-03-16 16:49:34)

    olive, now you're making even less sense. I didn't say the sleep example was stupid and I didn't question your reasons for doing/wanting this.
    I suggested you add "Before=display-manager.service" and you respond "I added Before=graphical.target and it didn't change anything."
    I also tried to explain why systemd has no reason to delay the display-manager.service. You could have asked for further clarification, as berbae has now done. Let's try a longer explanation.
    Service startup
    Services can be started in different ways, as configured with Type=. This determines when a service is considered "started" (or when the service's start-up is considered finished). When a service reaches this state (some time after being started), units that are supposed to start After= this service will be started (and no sooner).
    With simple systemd has no further information about the start-up process. It launches whatever you specify in ExecStart and this is the main process that continues to run till the service stops. systemd assumes this type of service is started immediately. All the other types have some way for the process to indicate to systemd (either directly or indirectly) when it has finished starting.
    Actually oneshot is also a bit special and that is where RemainAfterExit comes in. For oneshot, systemd waits for the process to exit before it starts any follow-up units (and with multiple ExecStarts I assume it waits for all of them). So that automatically leads to the scheme in berbae's last post. However, with RemainAfterExit, the unit remains active even though the process has exited, so this makes it look more like "normal" service with
    begin of unit/startup ---- end of startup ------ end of unit
    This is the relevant behavior for this thread. First sleep starts, then after 1000 seconds, start-up finishes and follow-up units will be started. Then either the unit dies, or (with RemainAfterExit) it stays "active".
    The man page describes how "end of startup" is determined for each Type.
    Targets
    Targets are meant to group units together, to provide synchronization points (and replace runlevels). When you start a target, all its units will be started (in parallel if possible). The man page says:
    Unless DefaultDependencies= is set to false, target units will
           implicitly complement all configured dependencies of type Wants=,
           Requires=, RequiresOverridable= with dependencies of type After= if the
           units in question also have DefaultDependencies=true.
    This means that (by default) when a target is requested, all it units are started first. Only after all units have finished starting, the target itself will be started (and since the target doesn't do anything by itself, this startup is basically instantaneous). Without this dependency, the order between the target and its units is unspecified, so in theory the target could finish starting immediately while its units are still being started.
    Back to olive
    graphical.target has these DefaultDependencies, so it is not started until all its units (like display-manager.service) and other After= dependencies (like multi-user.target) have finished starting. Your sleep service has to be started before multi-user.target starts (again due to default target dependencies). So first display-manager and the sleep service are started and after 1000 seconds, the sleep service finishes starting and then (assuming all other dependencies were quicker) multi-user.target is started and graphical.target as well (assuming display-manager didn't need 1000 seconds).
    If you want display-manager.service after the sleep service, add a Before/After line to specify that (this was your original goal and my suggestion).
    olive wrote wrote:However, units that are parts of the graphical target are still launched before the graphical target become active. I am still unable to completely delay the starts of the graphical target before a specific unit completes.
    It should be clear now how this works. "units that are part of the graphical target" can only mean "units that are wanted/required by the graphical target" but that is basically all the units that are started when you boot your system, because multi-user.target is a part of graphical.target. And your sleep service is a part of multi-user.target, so in fact you're saying you want to delay starting the sleep service until the sleep service completes
    What you probably intended was to delay all units that are a part of graphical.target but not of multi-user.target until after the sleep service. I can't think of an easy (or even good) way to do this and this post is already too long, so I'll table that for now.

  • Waiting on unknown threads to finish

    I have made the ExecutionService class, and now i have a small problem. The point of the class was to split the job normally done by one thread into as many as possible. Now, i need the thread that called executeInstantly/waitToExecute to wait until the requested task(s) are done, and there are no more tasks to process. What would be the best way to implement that? Note, only one thread will be adding to the Queue of tasks, and its the same one that needs to wait on them to finish.
    package jad.util;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    public class ExecutionService {
        public ExecutionService() {
            runnableTasks = new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE);
            initializeExecutors(Runtime.getRuntime().availableProcessors());
        public ExecutionService(BlockingQueue<Runnable> blockingQueue) {
            runnableTasks = blockingQueue;
            initializeExecutors(Runtime.getRuntime().availableProcessors());
        public ExecutionService(final int NUM_THREADS, final int MAX_JOBS) {
            runnableTasks = new LinkedBlockingQueue<Runnable>(MAX_JOBS);
            initializeExecutors(NUM_THREADS);
        private final void initializeExecutors(final int NUM_THREADS) {
            for (int i = 0; i < NUM_THREADS; i++) {
                createNewExecutor();
                ++numThreadsRunning;
        private final Runnable getPermTask() {
            return new Runnable() {
                @Override
                public void run() {
                    Exception ex = null;
                    try {
                        while (continueRunning) {
                            getNewTask().run();
                    } catch (InterruptedException e) {
                        (ex = e).printStackTrace();
                    } catch (Exception e) {
                        (ex = e).printStackTrace();
                    } finally {
                        if (ex != null) {
                            createNewExecutor();
        private Executor createNewExecutor() {
            return new Executor(getPermTask());
        private Runnable getNewTask() throws InterruptedException {
            return runnableTasks.take();
        public boolean executeImmediately(Runnable task) throws Exception {
            if (!continueRunning) {
                throw new Exception("ExecutorService instance is shut down");
            return runnableTasks.offer(task);
        public void waitToExecute(Runnable task) throws InterruptedException, Exception {
            if (!continueRunning) {
                throw new Exception("ExecutorService instance is shut down");
            runnableTasks.put(task);
        public void shutDown() {
            continueRunning = false;
            Runnable emptyTask = new Runnable() {
                @Override
                public void run() {
                    return;
            for (int i = 0; i < numThreadsRunning; i++) {
                try {
                    waitToExecute(emptyTask);
                } catch (InterruptedException e) {
                    System.out.println("Could not shut down!");
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
        private int numThreadsRunning = 0;
        private volatile boolean continueRunning = true;
        private BlockingQueue<Runnable> runnableTasks;
    class Executor {
        public Executor(Runnable task) {
            Thread t = new Thread(task);
            t.setDaemon(true);
            t.setName("Executor service thread");
            t.start();
    }Edited by: Jadz_Core on Aug 6, 2009 9:36 PM

    You would use a java.util.CountDownLatch if you only wanted to wait for the tasks currently executing and waiting in the queue (for example, there would be no tasks added AFTER the waiting began). I think this is suitable for your situation since you said there would be just one thread adding to the queue.
    Pseudocode:
    class ExecutorService {
        private volatile CountDownLatch counter = new CountDownLatch(Integer.MAX_VALUE);  //start countdown latch at really high values
        private AtomicInteger activeThreadCount = new AtomicInteger(0); //keep track of threads actually working
        private BlockingQueue queue; //keep waiting tasks
        class PermTask implements Runnable
            public void run()
                while (!shutdown)
                    Runnable task = queue.take();
                    activeThreadCount.incrementAndGet();
                    try
                        taskToRun.run();
                    finally
                        activeThreadCount.decrementAndGet();
                        counter.countDown();
        public void waitForTasksToComplete()
            int totalTasks = queue.size() + activeThreadCount.get();
            counter = new CountDownLatch(totalTasks);
            counter.await();
        }This would take a bit of cleaning up, for instance you have to protect the activeThreadCount and the counter so that the values don't change in the middle of some work (a ReadWriteReentrantLock might work nicely here - the PermTask would acquire Read Locks so they don't block each other. The wait... method acquires a Write lock to it waits for Reads to finish, and blocks more Reads until it is done). But it should get you started.
    Edited by: stevejluke on Aug 7, 2009 7:01 AM

  • Standby media recovery waiting for inactive thread

    Hi,
    Please let me know any idea on this scenario. Thanks.
    Environment:
    Oracle 11.2.0.2
    primary: 3 node RAC
    standby: 3 node RAC
    Problem:
    there is thread 5 (not registered instance or did not show in srvctl) that generates archivelog. but the lag apply stopped because of this when the instance (of thread 5) is shutdown.
    question: somehow an instance is registered in the cluster but in srvctl only 3 instance is running. it should have 4 instance but 1 is not running. How can I remove the thread 5 so when someone startup then shutdown instance#4 it will not create archivelog that will stopped the apply of archivelog in standby.
    note: this is perf environment server so someone and "other" DBA is accessing this environment which I am not aware what are they doing with the cluster.
    looking in alert log file: - it is waiting for thread 5 sequence 510. But the instance is down so log is not shipped to standby database and this resulted to lag in other threads.
    Sat Aug 03 18:54:47 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_1_seq_13718.1544.822333555
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_2_seq_17665.22678.822315375
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15465.14138.822313997
    Media Recovery Waiting for thread 5 sequence 510
       THREAD# LAST_SEQ_RECEIVED LAST_SEQ_APPLIED
             1             13745            13717
             2             17728            17664
             3             15527            15464
             5               509              509
    what I did is:
    1. primary (asm copy to file system)
    2. scp primary to standby
    3. standby (file system copy to asm)
    4. rman target / -> catalog archivelog <thread 5 sequence 510)
    5. then looking into alert log file; it performed media recovery
    Sat Aug 03 23:03:13 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_1_seq_13718.1544.822333555
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_2_seq_17665.22678.822315375
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15465.14138.822313997
    Media Recovery Waiting for thread 5 sequence 510
    Sat Aug 03 23:15:21 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_5_seq_510
    Sat Aug 03 23:15:32 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15466.10925.822316315
    Sat Aug 03 23:17:18 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_2_seq_17666.853.822333143
    Sat Aug 03 23:18:39 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15467.834.822333553
    Sat Aug 03 23:20:54 2013

    in Standby, thread 4 and 5 are both UNUSED, and size is incorrect (not equal to other redo log). I want to recreate it but cannot drop redo log. I follow Doc ID 740675.1.
    any idea what are the missing steps? thanks.
    ORA-01624: needed for crash recovery of instance UNNAMED_INSTANCE_5 (thread 5)
    select group#,thread#,archived,status,bytes from v$log;
    primary DB:
        GROUP#    THREAD# ARC STATUS                BYTES
             1          1 YES INACTIVE         1073741824
             2          1 YES INACTIVE         1073741824
             3          2 NO  CURRENT          1073741824
             4          2 YES INACTIVE         1073741824
             5          3 YES INACTIVE         1073741824
             6          3 YES INACTIVE         1073741824
             7          2 YES INACTIVE         1073741824
             8          1 NO  CURRENT          1073741824
             9          3 NO  CURRENT          1073741824
            10          4 YES INACTIVE         1073741824
            11          4 NO  CURRENT          1073741824
        GROUP#    THREAD# ARC STATUS                BYTES
            12          4 YES INACTIVE         1073741824
            13          5 YES INACTIVE         1073741824
            14          5 YES INACTIVE         1073741824
            15          5 NO  CURRENT          1073741824
    standby DB:
        GROUP#    THREAD# ARC STATUS                BYTES
             1          1 YES INACTIVE         1073741824
             2          1 YES INACTIVE         1073741824
             3          2 NO  CURRENT          1073741824
             4          2 YES INACTIVE         1073741824
             5          3 YES INACTIVE         1073741824
             6          3 YES INACTIVE         1073741824
             7          2 YES INACTIVE         1073741824
             8          1 NO  CURRENT          1073741824
             9          3 NO  CURRENT          1073741824
            10          4 YES INACTIVE         1073741824
            11          4 NO  CURRENT          1073741824
        GROUP#    THREAD# ARC STATUS                BYTES
            12          4 YES INACTIVE         1073741824
            13          5 YES INACTIVE         1073741824
            14          5 YES INACTIVE         1073741824
            15          5 NO  CURRENT          1073741824

  • Waiting for multiple threads to complete.......

    Search the forum archives but have not found a definitive solution...
    I have java app which spawns many threads (runnable objects) in the main() method. As one would expect, main exits before the threads finish but I don't want this to happen. I want to wait until all the threads have completed so I can use the results (stored in a vector) in the main thread....kindof like waitformultipleobjects in windows NT...
    does any guru out there know how best to achieve this????
    thanks

    Have you tried using a ThreadGroup? I imagine something like the following. I think it is not so nice because of the empty while loop but you get the idea.
    public class ThreadGroupTest {
         private static class Dummy extends Thread{
              private long sleepms;
              private String msg = null;
              public Dummy(ThreadGroup tg,long sleepms){
                   super(tg,"test"+String.valueOf(sleepms));
                   this.sleepms = sleepms;     
              public void run(){
                   try {
                        Thread.sleep(sleepms);
                   } catch (InterruptedException e) {
                   this.msg="Slept "+String.valueOf(sleepms)+" millis.";
              public String getMsg() {
                   return msg;
         public static void main(String[] args) {
              Dummy[] threads = new Dummy[10];
              ThreadGroup tg = new ThreadGroup("test");
              for(int i = 0;i<10;i++){
                   threads[i] = new Dummy(tg,(i+1)*1000);
                   threads.start();
              while(tg.activeCount()>0){
                   System.out.println(tg.activeCount());
              for(int i=0;i<threads.length;i++){
                   System.out.println(threads[i].getMsg());
    Hope that helps.

  • Asynchrono​us Call - collect values without waiting for sub VI to finish executing

    Hi All, I'm relatively new to LabVIEW and for the first time I'm attempting to make use of Asynchronous calls in a program.
    What I would like to accomplish, generally, is this: At the beginning of the main vi, begin running a sub-vi in the background. This sub-vi is collecting streaming data from an instrument with a refresh rate of 50Hz. At various points in the main vi I would like to call the instantaneous value of that streaming data from the sub vi, passing it back into the main vi, while allowing the sub-vi (the streaming data collection) to continue running. The reason for this, is that I need to collect the data from this instrument many times wihtin a loop, and the connection initialization to the streamin data instrument is both slow and faulty, and takes too long if I have to initialize the connection, collect the data, close the connection, each time I wish to collect the data. I would prefer to initialize the connection once at the beginning, have a stream of continuous data being collected in the background, and then at certain points within the main vi loop, query that streaming data for its instantaneous value, but allow the streaming data sub vi to continue running.
    I recognize that a method to allow the streaming data collection sub vi to run in the background is to use the Asynchronous call method - however, to collect the data I need to use an asynchronous wait, which will only collect the data if the streaming data sub vi finishes executing. How can I collect the data at a particular instant while still allowing the subvi to keep running (thereby minimizing the number of times the connection to the instrument needs to initialized)?
    Any suggestions or alternative methods would be great!
    Thanks
    Jason

    This is typically solved in a different way than what you envision. Have your parallel deamon post its current values to a buffer. This could be a global variable (gasp!!) or an intelligent global variable (a VI with loop that executes always once and has an unitialized shift register that can either be initized or read based on a control input). You can add extra code to the read and write selection such as scaling etc to turn the intelligent global into an action engine that does extra things on its different methods.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions
    Attachments:
    Intelligent Global.vi ‏19 KB

  • Wait for all threads in a array to die

    I everyone. I'm from Portugal and I have some experience in JAVA programming (approximately five years) but this is the first the first time that i'm trying to use threads. I'm trying to learn writing some simpler code that does almost exactly at the basic level the same stuff that a complex application that I need to write for my work.
    What I'm trying to do is execute a counter that counts all operations in threads belonging to the same array (an array of n threads).
    A static variable in the Thread class (implementing Runnable) counts all operations performed by all threads and sums them all and shoud display the total of operations after all threads terminate, but this exactly what I don't know how to do:
    This is my example code:
    public class TT1 implements Runnable {
         int id;
         double last_number;
         static int threads_counter = 0;
         static int total_threads = 4;
         static long total_numbers;
         int total_randoms = 1000;
         public void run() {
              for (int i=0;i<total_randoms;i++)
                   total_numbers++;
                   // does some stuff, in this case, generate a random number!
                   last_number = Math.random();
              System.out.printf("Thread %d:%f(%d)\n",id,last_number,total_numbers);
         public TT1() {
              id = threads_counter++;
              new Thread(this).start();
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Thread [] threads = new Thread[total_threads];
              for (int i=0;i<threads.length;i++)
                   threads[i] = new Thread(new TT1());
              /* commented code using join(), is not working or I don't know
              how to use it! */
              for (int i=0;i<threads.length;i++)
                   try {
                        threads.join();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              try {
                   threads[total_threads-1].join();
              } catch (InterruptedException e) {
                   e.printStackTrace();
              // this line should be executed ONLY after ALL threads have died!
              System.out.println("******GENERATED NUMBERS TOTAL:" + total_numbers);
    Somebody can give me a hint how to solve this ?

    Thanks for your replies.
    Actually, i've corrected the code, now i'm starting the threads outside the constructor. Originally I thought this could be a simpler way to create the threads: launching them at same time I'm creating them! Is this wrong ? :) Well, watching the results.
    I changed my code:
    public class TT1 implements Runnable {
         int id;
         double last_number;
         static int threads_counter = 0;
         static int total_threads = 4;
         static long total_numbers;
         int total_randoms = 1000;
         public void run() {
              for (int i=0;i<total_randoms;i++)
                   total_numbers++;
                   // does some stuff, in this case, generate a random number!
                   last_number = Math.random();
              System.out.printf("Thread %d:%f(%d)\n",id,last_number,total_numbers);
         public TT1() {
              id = threads_counter++;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Thread [] threads = new Thread[total_threads];
              /* create individual threads */
              for (int i=0;i<threads.length;i++)
                   threads[i] = new Thread(new TT1());
              /* launch the threads (NEW CODE) */
              for (int i=0;i<threads.length;i++)
                   threads.start();
              /* commented code using join(), is not working or I don't know
              how to use it! */
              for (int i=0;i<threads.length;i++)
                   try {
                        threads[i].join();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              // this line should be executed ONLY after ALL threads have died!
              System.out.println("******GENERATED NUMBERS TOTAL:" + total_numbers);
    And I obtain the output:
    $ java TT1
    Thread 0:0,191546(1000)
    Thread 1:0,937476(2000)
    Thread 2:0,825079(3000)
    Thread 3:0,451367(4000)
    ******GENERATED NUMBERS TOTAL:4000Exactly as I want it!
    All is good when it works good ;)
    Best regards

  • I downloaded my Adobe Creative Suite 5.5 design standard, student and teacher licensing and it load ed.  I am waiting for an email to finish up but I have not received it yet,  I had the serial number entered in and everything should have been good to go.

    I downloaded my Creative Suite 5.5 student teacher licensing software.  I all loaded fine in my Mac but at the end of the download it gave me a message that I would need to check my e-mail for further steps in order to be able to use the software.  I have not received this e-mail yet.  I had my email listed as <Removed by Moderator>
    Is there something that I need to show as proof of being a student yet?   I had to give my student id number in order to get the serial number.  I did not use my student e-mail address though. If that is the issue I can supply that also.  <Removed by Moderator>
    Help.  Please

    Erdygirl please be aware you are posting to a public forum.  I have removed your personal information from your previous post.
    Please check your account at http://www.adobe.com/ to locate your serial number.  You can find more information on how to locate your serial number at Find your serial number quickly - http://helpx.adobe.com/x-productkb/global/find-serial-number.html.

Maybe you are looking for

  • Sharepoint thumbnails in Reporting Services

    Hello, In a reporting services report, if I add an external image stored in a image library in Sharepoint 2007 Standard Edition (let's say http://myserver/ImagesLib/Image.jpg), the image is correctly displayed in the report viewer in visual studio 20

  • AVCHD presets in CS5 where? + Settings...

    Am I being dumb, or do I need to load them from somehwere I have no AVCHD preset in the sequence or general tab when I create a new project ( in sequence I have DV24, DV NTSC, DV pal, DVC pro 50HD, Mobile and devices) Finding it hard to find resource

  • Run a LabVIEW VI from VB without compiling

    I've got a couple of LabVIEW VI's that I want to run from VB without having to compile them.  I can run them fine on the development machine using:     CreateObject("LabVIEW.Application") When I try this command on another machine that has the LV Run

  • Transfering recieved files to the memory-card!!!!

    Hi, I transfer files/pictures to my E71 via the Bluetooth but have a couple of problems! 1- If the file is bigger then the available phone memory (max 110 meg!) then i can't transfer! That i understand but does it exist any way to configure the phone

  • ADF View Controller - Page Transitions

    Hi All, Definitley releveant here - JSF 2.0 / Jdev 11.1.2 This one may be considered a little left of filed, but has anyone out their played around or implemented view controller transitions? Depending upon the network speed, with a lot of my pages,