Reuse a waiting/blocked thread

Using the API in java.util.concurrency, there are operations such as BlockingQueue.take() or Condition.await() that makes the current thread to be blocked (waiting) on the operation to complete. I am working on a problem in which, in such situation, it is very costly to leave the thread as such holding all the resources already allocated for it. I would like to use the same thread to run/execute another task. And, when the condition or take can continue their work, then the resources are allocated back to the thread (including the local state) such that the thread can continue the execution from the blocked/waiting point. So, my question is that is there any way to release the thread when it is blocked on some concurrent operation such that it can be used for other executions?
On a related ground, is there any way I can replace the Thread class implementation in Java/JVM?
My current impression is that since some parts of the implementations are native so we need to tweak the C++ code, is that correct?
Thanks in advance.

i think you are missing the point of what i'm saying. i'm saying you don't need to change how threads work, you need to change your style of programming. having multiple tasks run on the same physical thread is as easy to do in java as it is in erlang (as Peter Lawrey described). what you need to do is use the erlang style of programming, where a thread does not block waiting for something to happen, but is instead giving a task when there is work today. i.e. you need to write your tasks so that they are essentially non-blocking. you can do this just fine in java without mucking w/ the jvm.
for instance, say you have a standard model with 3 queues, 3 producers, and 3 consumers, where there is 1 producer and 1 consumer per queue, and the consumer is a dedicated thread. in this scenario, if a queue is empty, that thread is idle/useless. instead, you can change your model around so that instead of each producer putting "data" on the queue, they instantiate a "handler/consumer" (instance of Runnable) with a reference to the data to be handled. this handler is then tossed into a thread pool with 3 threads. in this scenario, your 3 threads are now "general purpose" and can work on whichever queue(s) happen to currently have data. (in essence, you are collapsing your 3 queues into 1 queue and making the queue data "smarter"). this is exactly what erlang is doing under the hood.
Edited by: jtahlborn on Jul 28, 2011 11:34 AM

Similar Messages

  • Stopping a blocked Thread

    I need to stop a Thread, or interrupt a blocked I/O.
    I'm making a call to a library that I do not own and cannot change. The library makes a HTTP connection to a service and waits for a response. As far as I know, the library uses BufferedReader to read the service response. If the service is down, then no response is ever returned, and the BufferedReader read simply blocks.
    I cannot change the library to be intelligent, of course, and don't have very good luck getting the service support to fix their stuff. But I have to use the library. How can I interrupt the blocked I/O read?
    What I've tried is as follows, but I'm not convinced it's the right way. My application is a long-running application that does not exit very often, so I'm concerned also about gc not properly recycling the resources due to still having the blocked thread still there (and this has impacted subsequent executions, even though I use local variables where I can).
            // Create a new Thread to wait on the submission
            Thread t = new Thread() {
                public void run() {
                    response = event.submit();
            t.setDaemon(true);
            t.start();
            try {
                t.join(timeOut);
                msg = "Attempt to connect to ESM Server timed out";
            catch (InterruptedException e) {
                msg = e.getMessage();
            }The other option I was thinking of, was coding my call to ESM server in a separate Class with a main, and invoking it via Runtime.exec. That way, at least I'm 100% sure that the code exits, and I can use System.out/err to receive the "output".
    Given that Thread.stop() is deprecated, and that you theoretically cannot interrupt blocked I/O, how have others solved this problem?
    Thanks,
    Matt

    ...you theoretically cannot interrupt blocked I/O, how have others solved this problem?I've done it your way. Each thread does an access. If it takes too long, then it may never respond and I ignore it. I also log the error condition and try to notify and administrator.
    Threads probably take up about a megabyte of memory so I may run out of memory it the problem doesn't get fixed by manual intervention.
    Your idea of using Runtime means that you create a new JVM for each ESM. If a thread takes up a megabyte, the new JVM takes up many, many megabytes. Instead of running out of memory in the JVM, you may run out of memory in the Box.
    Every situation is different. My thread approach works for my application. What works best for you is your call.

  • Media Recovery Waiting for thread 1 sequence (in transit)

    I have rebuilt our standby database using an rman duplicate since it was missing many archive logs.
    Following the duplicate, the standby is now almost in sync with the primary. Logs are shipping across but are not being applied in a timely manner. How long should it take for an archive log from the primary to be applied to the standby?
    I need to know this so that a proper script can be set up to check the primary and standby. At the moment they are never exactly in sync - always one sequence number behind the primary.
    Why is the standby is not applying in a timely manner?
    From the alert log:
    Media Recovery Waiting for thread 1 sequence 11278 (in transit)
    The log seems to be "in transit" for a long time
    PRIMARY:
    SQL> select max (sequence#) current_seq from v$log;
    CURRENT_SEQ
    11278
    SB:
    SQL> select MAX (SEQUENCE#), APPLIED FROM V$ARCHIVED_LOG where APPLIED ='YES' GROUP BY APPLIED;
    MAX(SEQUENCE#) APP
    11277 YES
    ALERT LOG:
    RFS[2]: Archived Log: '/backup/prod/log_1_11277_704816194.dbf'
    Primary database is in MAXIMUM PERFORMANCE mode
    Mon Nov 1 15:22:01 2010
    Media Recovery Log /backup/prod/log_1_11272_704816194.dbf
    Mon Nov 1 15:26:49 2010
    Media Recovery Log /backup/prod/log_1_11273_704816194.dbf
    Mon Nov 1 15:29:54 2010
    Media Recovery Log /backup/prod/log_1_11274_704816194.dbf
    Mon Nov 1 15:34:18 2010
    Media Recovery Log /backup/prod/log_1_11275_704816194.dbf
    Mon Nov 1 15:36:42 2010
    Media Recovery Log /backup/prod/log_1_11276_704816194.dbf
    Mon Nov 1 15:39:43 2010
    Media Recovery Log /backup/prod/log_1_11277_704816194.dbf
    Mon Nov 1 15:42:34 2010
    Media Recovery Waiting for thread 1 sequence 11278 (in transit)
    I should add that I understand that for the Primary and Standby to be out by one log is not cause for concern (they are applying). Its just that I wanted to script a check that would compare them both, and and the moment they are never equal - when I understand that they should be and that the logs should be applied almost immediately.
    Edited by: Dan A on Nov 1, 2010 4:36 PM

    How long should it take for an archive log from the primary to be applied to the standby?depends on network speed also.
    make sure the archives are shipped to standby location.
    PRIMARY:
    SQL> select max (sequence#) current_seq from v$log;
    CURRENT_SEQ
    11278(this is log not archivelog ) ..... :)SB:
    SQL> select MAX (SEQUENCE#), APPLIED FROM V$ARCHIVED_LOG where APPLIED ='YES' GROUP BY APPLIED;
    MAX(SEQUENCE#) APP
    11277 YES
    Hi check is MRP started or not?
    primary database you need not check current sequence, check last generated sequence..not current sequence.
    current sequence is redo log which has been not yet archived
    I think everything is perfect here.. no issues.
    Hope you understood, let me know if not clear , thanks.

  • Obtaining monitor lock of a blocked thread

    Is there a way to obtain the monitor lock (reference to the object) of a blocked thread? Something like Object Thread.getMonitorLockedObject()Also when you get the locked object it would be useful if you can get reference to the thread which is holding it, e.g.
    Thread Object.getLockingThread() although the latter could be achieved through iterating over all threads and calling boolean Thread.holdsLock(Object)Such methods would help very much in debugging deadlocks and other concurrency problems.

    <pre>
    Is there a way to obtain the monitor lock (reference
    to the object) of a blocked thread? Something like
    Object Thread.getMonitorLockedObject()
    Not that I'm aware of, and a quick glance through the APi didn't look promising.
    Also when you get the locked object it would be
    useful if you can get reference to the thread which
    is holding it, e.g.
    Thread Object.getLockingThread()although the latter could be achieved through
    iterating over all threads and calling boolean
    Thread.holdsLock(Object)
    Again, no. And your work-around wouldn't work, since the holdsLock method is static and can only be called for the current thread.
    Such methods would help very much in debugging
    deadlocks and other concurrency problems.There already are some useful methods for that in the Thread class, e.g. getState() and getAllStackTraces().
    </pre>

  • How to see and clear the blocked threads

    Where can I see how many threads are currently running and how many threads are blocked and how many are in idle status.
    Where can I see all these information and if I want to kill the blocked threads how to do that
    Thanks in advance

    This can be found in Weblogic Log folder..

  • Update of jlabel does not happen when i wait for thread to finish (join())

    gurus please help.
    I have a main application which in actionevent calls a thread, that thread calls parent method to update ths status in jlabel, but when i use thread.join() to wait for process to complete, the jlabel does not get updated, please tell me how can i update the jlabel, i have to wait for thread to finish and during run i need to update the jlabel.
    thanks

    hi camickr and gurus:
    here is the code:
    notice after pressing the Process button, the label is being updated but its not working. I called the processnow() method directly and also by thread, but in thread I have to wait until it finishes using join() but still does not work, please help. Thanks
    package label;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class thePanel extends JDialog {
      private DefaultTableModel tableModel = null;
      private JTable theTable = new JTable();
      private JScrollPane scrollPane = new JScrollPane();
    JPanel tPanel = new JPanel();
      private Border mainBorder;
      private BorderLayout borderLayout1 = new BorderLayout();
      private BorderLayout borderLayout2 = new BorderLayout();
      private BorderLayout borderLayout3 = new BorderLayout();
      private BorderLayout borderLayout4 = new BorderLayout();
      private JPanel statusPanel = new JPanel();
      private JPanel buttonPanel = new JPanel();
      private JPanel lowerPanel = new JPanel();
      private JLabel statusBar = new JLabel();
      private JButton processButton = new JButton("Process");
      public JButton closeButton = new JButton("Close");
      boolean image = true;
      theProcess processThread;
      Vector tableData = new Vector();
      ImageIcon Image = new ImageIcon("image.gif");
      ImageIcon oImage= new ImageIcon("oimage.gif");
      boolean errorOcurred=false;
      String statusMessage;
      public thePanel() {
        try {
         jbInit();
        } catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        tPanel.setPreferredSize(new Dimension(800,424));
        mainBorder = new TitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)," ");
        statusPanel.setBorder(BorderFactory.createEtchedBorder());
        tPanel.setBorder(mainBorder);
        tPanel.setLayout(borderLayout1);
        scrollPane.getViewport().add(theTable, null);
        tPanel.add(scrollPane,  BorderLayout.CENTER);
        // status
        statusPanel.setLayout(borderLayout2);
        statusPanel.setBorder(BorderFactory.createEmptyBorder());
        statusBar.setAlignmentX((float) 0.5);
        statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
        statusBar.setMaximumSize(new Dimension(600, 21));
        statusBar.setMinimumSize(new Dimension(600, 21));
        statusBar.setPreferredSize(new Dimension(600, 21));
        statusPanel.add(statusBar, BorderLayout.SOUTH);
        // buttons
        processButton.setPreferredSize(new Dimension(70,25));
        processButton.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            process_actionPerformed(e);
        closeButton.setPreferredSize(new Dimension(70,25));
        buttonPanel.setLayout(borderLayout3);
        buttonPanel.setBorder(BorderFactory.createRaisedBevelBorder());
        buttonPanel.add(processButton,BorderLayout.WEST);
        buttonPanel.add(new JPanel());
        buttonPanel.add(closeButton,BorderLayout.EAST);
        // lower panel
        lowerPanel.setLayout(borderLayout4);
        lowerPanel.setBorder(BorderFactory.createEmptyBorder());
        lowerPanel.add(statusPanel, BorderLayout.WEST);
        lowerPanel.add(buttonPanel, BorderLayout.EAST);
        tPanel.add(lowerPanel, BorderLayout.SOUTH);
        theTable.setAutoCreateColumnsFromModel(true);
        theTable.setColumnSelectionAllowed(false);
        theTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        theTable.getTableHeader().setReorderingAllowed(false);
    getContentPane().add(tPanel);pack();
        getinfo();
    show();
      private void prepairTable(){
        tableModel = new DefaultTableModel(){
                          public boolean isCellEditable(int row, int col)
                            { return false; }};
        tableModel.addColumn("text 1");
        tableModel.addColumn("text 2");
        tableModel.addColumn("text 3");
        tableModel.addColumn("text 4");
        tableModel.addColumn("text 5");
        theTable.setModel(tableModel);
      } // end method (prepairTable)
      public void refreshTable() {
        prepairTable();
      public void getinfo() {
        try {
            refreshTable();
            tableModel.addRow(new Object[]{"3465465555","0123456789",new Date(1135022905196L),"0100000","errror message","sssssss"});
            tableModel.addRow(new Object[]{"8949344562","0324354549",new Date(1134511763683L),"0166600","errror mes666e","ddddddd"});
    setStatusMessage("ready to process, select record and click Process button to process record");
          errorOcurred = false;
        } catch (Exception ex) {
          errorOcurred = true;
          ex.printStackTrace();
        } // End try
      private void process_actionPerformed(ActionEvent e) {
        try {
          if(theTable.getSelectedRows().length > 0) {
    //        processThread = null;
    //        processThread = new theProcess(this);
    //        processThread.start();
    processnow();
            System.out.println("........finished now.........");
          } else {
        } catch (Exception ex) {
          ex.printStackTrace();
      public void processnow() {
        try {
          int[] selectedRows = null;
          int totalSelected = 0;
          setStatusMessage("processing " + totalSelected + " selected records...");Thread.sleep(1500);
          selectedRows = theTable.getSelectedRows();
          totalSelected = selectedRows.length;
          for(int i = 0; i < totalSelected ; i++){
            setStatusMessage("processing " + (i+1) + " of " + totalSelected + " selected records...");
            System.out.println(".......................row: "+selectedRows);
    Thread.sleep(2500);
    System.out.println("........fins...........");
    errorOcurred = false;
    } catch (Exception ex) {
    errorOcurred = true;
    ex.printStackTrace();
    } // End try
    public void setStatusMessage(String message) {
    statusMessage=message;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    if(image)
    statusBar.setIcon(Image);
    else
    statusBar.setIcon(oImage);
    statusBar.setText(statusMessage);
    statusBar.update(statusBar.getGraphics());
    public static void main(String[] args){
    new thePanel();
    } // class
    package label;
    import java.lang.Runnable;
    public class theProcess implements Runnable {
    private thePanel parent;
    public theProcess(thePanel xparent){
    parent = xparent;
    } // end constructor
    public void start() {
    try {
    Thread thisThread = new Thread(this);
    thisThread.start();
    thisThread.join();
    } catch(Exception ex) {
    ex.printStackTrace();
    } // end method (start)
    public void run(){
    try {
    parent.processnow();
    } catch (Exception ex){
    ex.printStackTrace();
    } // end try
    } // end method (run)
    } // end class

  • Blocked threads

    Hi, I need help to solve the following problem:
    I have a thread T calling a method x() of a class C.
    The problem is that, by my point of view, the method C.x() is an atomic function and it could be blocking or it could take too much time.
    Now I need to kill the thread after a while (i.e. after timeout expiration).
    I know that the Thread.close() method is deprecated and that, in this case, Thread.interrupt() can't solve the problem (I can't use status variables).
    I've also read something about java.nio package but I don't know how to use it.
    Is there anybody can help me?
    Thanks

    I'm implementing a simple server that gets request from clients.
    Clients open a socket connection on a well known port.
    When the server receives a new connection request it creates a new thread.
    This thread is in charge to receive, parse the commands coming from the client (via socket). Based on the request it calls the related method for the class. Normally the method is a call for a CORBA object's function. And the problem is that the response (that is, the function has finished) could come after a while and it is out of my control (for example CORBA objects has problems or the request itself takes time).
    After timeout expiration I need to kill all the blocked threads, because the server must handle a maximum number of threads, and if I don't kill blocked threads no other clients (requests) are admitted.
    thanks for your help
    d.

  • CPU going 100%. Can blocked thread may be a reason?

    Hi Team,
    May be a dumb question. In my application around 40 threads are in blocked state and CPU is going about 100%. Is blocked threads may be reason for that? As threads are blocked, CPU should not be busy entertaining them, that is the reason why this question came in mind. Can somebody clear my this doubt.
    Thanks in advance.

    I encounter the same problem, although I run Berkeley DB (Ver 6.0.20, C#) under .NET Framework and Windows server 2008(x64). Any BDB application of win32 runs well but will encounter trouble under platform of x64 when compile BDB to x64, even though the DLL compiled and linked with win32. The bug is that Berkeley DB take amount of memory as the size of databases and regardless of cacheSize. My estimation is that all memory for BDB malloced and NOT freed.

  • (J2ME) Stopping a blocked thread

    In J2ME, receiving a datagram blocks the current thread until a datagram is received. I have created a thread that simply receives a datagram and then loops waiting for the next one. How do I stop the thread when it is blocking in datagram receive waiting for a datagram to come in? I am using the code on http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html for a reference, and it mentions calling Thread.interrupt() but this method does not exist in J2ME.

    I tried searching for any API on J2ME... it looked like there were a lot of different specifications, and in any case I never found any API docs.
    However, i did want to say this:
    In regular java, the way you would normally do this is (ThreadObj).interrupt(), but you said this didn't exist. Are you 100% sure?
    If that's not working, I have 2 other ideas:
    1. Thread.stop() - it has been deprecated and is not technically "safe" but it could probably work in a pinch.
    2. There is often a way to put a timeout on an inputstream. See if you can do that.

  • WLS 8.1sp3 blocked threads halt MDB processing

    Under Weblogic Server 8.1 SP3 JMS consumers stop processing the JMS queues. This only started happening following our upgrade from SP2. We had numerous test baselines as well as months of production data to validate this.
              Specifically it appears that internal weblogic threads are blocked, preventing the MDBs (JMS consumers) from being dispatched. This doesn't immediately impact the user experience, but eventually unprocessed JMS messages accumulate and consume heap. You can figure out the rest.
              We had 5 MDBs working on this particular JMS queue, so under moderate traffic all 5 would need to be blocked before the problem was realized.
              As a work around, you'll need to request a patch from BEA. CR188391 appears to resolve this issue. You must request this however. BEA will not contact you - regardless of functional or economic impact.
              Thanks
              -Sean

    Sean,
              I've forwarded your comments internally. Usually, one can look in the release notes of future service-packs to see what's been fixed. I would think upgrading from SP3 to sp4, or even sp5 (the latest) would also have fixed the problem.
              Tom, BEA

  • Waiting for Thread to finish execution

    I have a program which uses a thread to copy files. While they are copying, a ProgressMonitor comes up displaying the current file being copied. After this has completed, my main program needs to be notified and go on with it's own code. Either I get the 'I'm done waiting!' message instantly, or not at all, instead of getting it after the thread completes. How do I do this?
    This is what I currently have
    // CLASS 1 //
    //...other code is here
    myMethod()
    ProgressMonitorDemo pmd = new ProgressMonitorDemo();
    while (!pmd.isDone())
    { wait(); }
    System.out.println( "I'm done waiting!" );
    }//Class 2 //
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    public class ProgressMonitorDemo extends JPanel
      public final static int ONE_SECOND = 1000;
      private ProgressMonitor progressMonitor;
      private Timer timer;
      private LongTask task;
      public ProgressMonitorDemo()
        task = new LongTask();
        timer = new Timer( ONE_SECOND, new TimerListener() );
        progressMonitor = new ProgressMonitor( this, "Running a Long Task", "", 0, task.getLengthOfTask() );
        progressMonitor.setProgress( 0 );
        progressMonitor.setMillisToDecideToPopup( 2 * ONE_SECOND );
        task.go( );
        timer.start();
      public boolean isDone()
        return task.isDone();
       * The actionPerformed method in this class
       * is called each time the Timer "goes off".
      class TimerListener implements ActionListener
        public void actionPerformed( ActionEvent evt )
          progressMonitor.setProgress( task.getCurrent() );
          String s = task.getMessage();
          if( s != null )
            progressMonitor.setNote( s );
          if( progressMonitor.isCanceled() || task.isDone() )
            progressMonitor.close();
            task.stop();
            Toolkit.getDefaultToolkit().beep();
            timer.stop();
    }// CLASS 3 //
    import javax.swing.*;
    import java.io.*;
    import java.awt.dnd.DnDConstants;
    public class LongTask
      private int lengthOfTask;
      private int current = 0;
      private boolean done = false;
      private boolean canceled = false;
      private String statMessage;
      public LongTask()
        //Compute length of task...
        //In a real program, this would figure out
        //the number of bytes to read or whatever.
        lengthOfTask = 400;
       * Called from ProgressBarDemo to start the task.
      public void go( )
        final SwingWorker worker = new SwingWorker()
          public Object construct()
            current = 0;
            done = false;
            canceled = false;
            statMessage = null;
            return new CopyMove();
        worker.start();
       * Called from ProgressBarDemo to find out how much work needs
       * to be done.
      public int getLengthOfTask()
        return lengthOfTask;
       * Called from ProgressBarDemo to find out how much has been done.
      public int getCurrent()
        return current;
      public void stop()
        canceled = true;
        statMessage = null;
       * Called from ProgressBarDemo to find out if the task has completed.
      public boolean isDone()
        return done;
       * Returns the most recent status message, or null
       * if there is no current status message.
      public String getMessage()
        return statMessage;
       * The actual long running task.  This runs in a SwingWorker thread.
      class CopyMove
        private String currOldLoc, currNewLoc, type;
        CopyMove()
          while( current < lengthOfTask )
            try
              Thread.sleep( 1000 );
              current += Math.random() * 100; //make some progress
              if( current > lengthOfTask )
                current = lengthOfTask;
              statMessage = "Completed " + current + " out of " + lengthOfTask + ".";
            catch( Exception e )
              System.out.println( "<ERROR>: Long Task " + e.toString() );
    }

    I tried this but it froze...
    public void myMethod()
    ProgressMonitorDemo pmd = new ProgressMonitorDemo( );
    synchronized( pmd )
       try
         pmd.wait();  
       catch(Exception e){}
    System.out.println( "I'm done waiting!" );
    }Class 2
    class CopyMove
      private String currOldLoc, currNewLoc, type;
      CopyMove()
        while( current < lengthOfTask )
          try
            Thread.sleep( 1000 );
            current += Math.random() * 100; //make some progress
            if( current > lengthOfTask )
              current = lengthOfTask;
            statMessage = "Completed " + current + " out of " + lengthOfTask + ".";
          catch( Exception e )
            System.out.println( "<ERROR>: Long Task " + e.toString() );
        synchronized(this)
          notifyAll();

  • Is it possible to release a blocked thread in Java or by JNI through JVM?

    Expert please help me, or where can I refer to find the correct answer.
    Thank you.

    Try Thread.interrupt() and/or explicitly closing the resource that it is blocking on.

  • Servlet waiting for threads to end

    Hi !
    To make our web app more efficient, we wanted to delegate some work to threads. But it seems that the servlet engine (or something else) is waiting for all spawned threads to end before sending the response back to the browser. So, if a servlet finishes execution but the threads it spawned are still working, I do not get the next page in the browser. I only do when all threads are done. So my question is : is this a normal behavior of the servlet engine ? If so, why ? If not, what could I have done wrong, what should I look out for when using threads inside servlets ?
    Thanks,
    Martin

    Yup I agree with the other guys.
    I am building a servlet that has 2 threads running continuously (looping), and they do not bother the requests/responses at all. But in your case if I understand correctly, you spawn threads from the request. You must have some kind of interaction between them.
    Are you sure you are spawning the code in a separate thread??. I use something like this:
    class Mythread extends Thread
    public void run()
    // code here
    THread threadobject = new Mythread();
    threadobject.start(); //( DO NOT CALL THE run() method, but the start() method.)
    Are your threads sleeping (to not hog up all CPU power???). Are your threads higher priority then the normal?.
    See ya,
    Andre

  • Waiting all threads in a fixed thread pool

    Hello, may I know how can I wait for all the threads in a fixed thread pool to be completed, without calling shutdownNow?
    Executor pool = Executors.newFixedThreadPool(nThreads);
    for(int i = 0; i < 10000;  i++)
        pool.execute(new StockHistoryRunnable(code));
    // blah blah blah
    // I would like to wait for all the 10000 task to be completed. There is a method named
    // awaitTermination. However, in order to use the method, I have to first call shutdownNow.
    // I do not want to do so, because I need to re-use the pool later.
    //

    You could retrieve all the "Future" instances returned by calling "submit" on your Executor and then have a Thread sequentially wait for the completion of all these individual tasks by using "get". Of course, this will require some synchronization if it is possible that new tasks get queued while you are already waiting for the original ones to be completed. But this way you can easily find out when all tasks have completed.

  • Problems with notify/wait on threads

    I have a few Player threads connected to some game server.
    The first player to connect ("Player1") starts a timer to 10 seconds. During this time all other connected players can't do anything. When the 10 seconds are up the game starts.
    My idea is that if the current thread is Player1 then it sleeps for 10 seconds and then calls notifyAll() to wake up all other player threads. Other player threads will wait() until they are notified by Player1. Problem is I can get Player1 to sleep and wake up but my notifyAll() calls don't wake the other players up.
    My basic server connection code:
    // a for loop to create players and add them to a vector ("players"). Run player threads as soon as they connect
    players.add( new Player( server.accept(), maze, this, i + 1);
    players.get(i).start();The run() for Players:
    public void run()
      synchronized( this)
        if( Thread.currentThread().getName.compareTo( "Player1") == 0)
          sleep( 10 * 1000);
          // game_started is a condition var, init to false
          game_started = true;
          notifyAll();
        else
          while( !game_started)
            try
              wait();
            catch( Exception e) {}
    }Somehow my others threads keep waiting even thought the notify signal has been sent. They just keep waiting.
    Any suggestions on what I'm doing wrong?

    Well the problem is that you seem a bit confused over the way wait and notify/notifyAll work.
    Wait (and notify) work with thread against an object monitor. What this means is that you need a common object shared among the threads that they are calling wait/notify on.
    Note that the Javadoc says this about wait
    wait() - Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.And about notifyAll
    notifyAll() - Wakes up all threads that are waiting on this object's monitor.So the problem is you have these threads waiting and notifying themselves. Which isn't what you want. See this section of [_the concurrency (threading) tutorial_|http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html] for more on how to use wait/notify/notifyAll.

Maybe you are looking for