Behaviour of wait()/notify()

Until recently, I was sure that notify wakes up only waiting threads. This is proven by this program:
class X extends Thread {     // Incomplete
    final Object lock;
    X(final Object lock) { this.lock = lock;  }
    static void log(String msg){ System.out.println((System.currentTimeMillis() - start) + ", " + Thread.currentThread().getName() + ": " + msg);}
    static void sleep1(long time) {     try {Thread.sleep(time);} catch(InterruptedException ie) {log("sleeping interrupt");}}
    public void run() {
        try {
            log("waiting");
            synchronized(lock) {
                lock.wait(); // halts forever
            log("waked up");
        catch(InterruptedException ie) {
            log("interrupted");
    static final    long start = System.currentTimeMillis();
    public static void main(String[] args) {
        Object lock = new Object();
        synchronized(lock) {lock.notify();} // notify
        new X(lock).start();  // create a thread to wait for the notification
}However, the following code breaks the rule:
class GamePlayer implements Runnable {     // Incomplete
    protected GamePlayer other;
    protected boolean myturn = false;
    protected synchronized void setOther(GamePlayer p) {
        other = p;
    synchronized void giveTurn() { // called by other player
        myturn = true;
        notify();          // unblock thread
    void releaseTurn() {
        GamePlayer p;
        synchronized(this) {
            myturn = false;
            p = other;
        p.giveTurn(); // open call
    synchronized void awaitTurn() throws InterruptedException {
        while (!myturn) wait();
    void move() { /*X.log("moving");*/ }
    public void run() {
        try {
            for (;;) {
                if (Thread.currentThread().getName().compareTo("two") == 0) {
                    X.log("sleeping");
                    X.sleep1(500);
                X.log("wainting");
                awaitTurn();
                move();
                X.log("releasing");
                releaseTurn();
         catch (InterruptedException ie) {} // die
    public static void main(String[] args) {
        GamePlayer one = new GamePlayer();
        GamePlayer two = new GamePlayer();
        one.setOther(two);
        two.setOther(one);
        one.giveTurn();
        new Thread(one, "one").start();
        new Thread(two, "two").start();
}The thread "one" initially owns the monitor, it makes a move and releases the monitor notifying the thread "two". However, the second thread is still sleeping. When it awakes from the sleep, the notification is already sent but the second thread receives it! That is, thread should not be waiting for the monitor event in order to recieve the notification. I'm I missing something?

Can anybody explain the need for synchronized blockin releaseTurn()?
Variable "myturn" is modified by the other thread.Yes, it is modified by another thread. But there is only one active thread. SingleWriterMultiReader paradigm does not block access to a shared resource, it just guards the access by permition granting. I do see any race conditions in releaseTurn() that would need for the synchro block on "myturn", "other" fields.
You need to synchronize both reading and writing of a
shared variable to ensure that one thread sees the
change made by another. This is the other fuction of
keyword "synchronized" (besides exclusive execution
of a block).However, notification is not sent in releaseTurn, it is done in giveTurn.
One more question, there is only one possible
situation to get notification (after myturn => true).
Will the program work properly without the cycle in
awaitTurn(): if (!myturn) wait();If you remove this statement, on the first iteration
both threads will go into wait() and there will be
no-one to notify them.The first thread will not wait, because it's "myturn" is true on the first iteration. It then gives turn to second. If secons have checked "myturn" before it will be waiting and the first thread will notify it. Alteratively, secon thread will check after the first thread had set it to true and will not wait again.

Similar Messages

  • Wait/notify, await/signal, faster blockingqueue that scales with N threads

    Hi,
    I have been benchmarking a blockingqueue. It holds 100 items before writers block. It uses not-empty/not-full semaphores. Typical stuff.
    I have noticed that with 1 writer and 1 reader threads, using synchronized()+wait/notify is faster than reentrantlock+await/signal.
    I tried to find the point (in number of W/R threads) where reentrant lock is better.
    For the remainder os the discussion, I must say that I never use 'fair' rentrantlocks: I tested them and they are always slower than synchronized.
    So, I always use 'unfair' locks.
    The thing is, the tests results are messed up. I mean I would expect a monotonous progression in reentrant lock performance as the number of W/R threads is increasing. But the reality (on a dual core dual opteron) shows strange progressions. Without diving into numbers...
    I would like to hear about the experiences of other people relatively to:
    -queue implementations and readers semaphore, writers semaphores most efficient patterns.
    -scalability observations and implementation choices related to the number of threads to be concurrent.
    Of course I have been experimenting with notify()/signal() instead of notifyAll()/signalAll() in order to avoid waking up too many writers/readers that do not stand a chance to perform their enqueue/dequeue without going back to wait()/await() again (in my case, fairness isn't an issue for readers, and for the moment, I accept unfair enqueue from writers). Also, a reader can notify/signal not only a waiting writer but another waiting reader if the queue isn't empty after its own dequeue. I'm about to do the dual notify/signal for writers: not only notify/signal a waiting reader but also another waiting writer if the queue isn't full after its own enqueue.
    Of course, this good-intentions implementation ends up notifying/signaling a lot. I'm searching for a new way of thinking, in case I have been blinded by too much obsession on my current implementation...! :-)
    Thanks.
    PS: for those of you that wonders why I don't use j.u.c array blocking queue, that's because I need:
    a) many queues enqueue to be able to notify/signal a single thread (1 thread waiting to read many queues). This implies an externally plugged-in readers (not-empty) semaphore.
    b) enqueueMany(array), dequeueMany(int max) ->array

    In Java 5 ReentrantLock provides much better performance under contention than built-in sync. Conversely built-in uncontended sync is always much faster. In Java 6 contended built-in sync has pulled back some ground on ReentrantLock. So with only two threads it is not surprising that built-in sync is faster.
    So the switch over point depends on the level of contention. This is a function of the number of threads (and CPU's) and what they do while holding the lock and between holding the lock.
    For evaluating read/write synchronization you need to have a read operation that is relatively long to dominate the cost the heavier read-lock. You also need sufficient parallelism to allow enough concurrent readers to make overall reader "throughput" significant.
    Benchmarks are seldom that useful/insightful unless realistic access patterns and workloads are used.

  • Why do we need to take a lock before invoking wait()/notify() on an Objec

    Hi,
    Why do we need to take a lock before invoking wait()/notify() on an Object? i know that we shud take otherwise illegalstateexception is thrown.
    what is the reason to take a lock bfefore invoking the above methods. why does jvm expects from the programmer?
    Cheers,
    duggana.

    Well, very often a wait or notify is conditional on the state of some flag (semaphore) which is protected by the monitor. By putting the wait in a synchronized section you guarantee that the sempaphore won't change between the final test of it and the actual wait or notify, otherwise a notify might be lost and the program hang.
    // wait on semaphor
    if (!canProcede)
       synchronized(this)
           if(!canProcede)
              wait();
    //   release semaphor
    synchronized(this)
         if(!canProceed) {
              canProede = true;
              notify();
        }If the wait above wasn't guarded by the sychrozined it's possible the second code fragment might be executed between the test and the wait, in which case the wait would be called after the notify and, hence, wait for ever.

  • Why do we need to take a lock before invoking wait()/notify() on an Object?

    Hi,
    Why do we need to take a lock before invoking wait()/notify() on an Object? i know that we shud take otherwise illegalstateexception is thrown.
    what is the reason to take a lock bfefore invoking the above methods. why does jvm expects from the programmer?

    Please do not crosspost..

  • Sleep or wait() / notify()  Which is better IYO

    Consider an app where a central object, like an information server is handed a query and an amount of time will pass before that information is available. For caching, many objects may ask the same question and be waiting on the same answer. Is it better to have the queries do a sleep loop to wait for the response or is it better for the queries to register with the server and call a wait(), then have the server issue a notify to objects that were waiting?
    Thanks for the advice.

    Thank you. I like sleep as well. Although with three little ones that can be a difficulty.
    I am having a difficulty with how to implement the wait notify. Can you tell me if the following is a good / bad / normal / horribly wrong example?
    // sorta code...
    // This class goes to a central location
    // or the network for an answer.  It represents one answer for one query.
    class InfoServerQuery extends Thread{
      volatile boolean isComplete = false;
      volatile String response = null;
      Vector pool = new Vector();
      public synchronized boolean isReady(Object obj){
        if(!isComplete){
          // Add object to answer pool
          pool.add(obj);
          return false;
        }else{
          return true;
      public void run(){
        try{
          // Get the information.......
          response = getInfo();
          // set isComplete
          isComplete = true;
          // notify all that are waiting.
          for(int a = 0; a < pool.size(); a++)
          synchronized(pool.get(a)){pool.get(a).notify();};
        }catch(Exception e){
          throw new RuntimeException();
    // This class asks the questions.
    class QueryClient{
      // instantiated in constructor
      InfoServerQuery q;
      public String getAnswer() throws Exception{
        while(!q.isReady(this)) synchronized(this){wait();};
        return q.response;
    }Thanks for any insights.

  • Simulating the wait/notify concept that Java has.

    Hi all,
    I need to simulate the wait/notify concept that Java has.
    My question is how do I get a Stored Procedure to wait (for a certain time period, once it times out the Stored Procedure can carry on but in an error state.) - (Like the "wait" in Java)
    And then another Stored Procedure to break this waiting state. (Like the "notify" Java).
    When the second stored procedure breaks the waiting state, the first stored procedure can carry on with it thread of execution.
    I have tried to use DBMS_Locks, but uncovered a few hiccups.
    Is there anything else I can try? ...
    Regards,
    Hilton

    Hi John,
    Thanks for the input, I have tried the using DBMS_Pipe and seems to have solved by problem.
    Will look into the DBMS_Alert as well.
    Thanks Again
    Hilton

  • Need help : wait() & notify()

    Hi, I am working on a project which has multiple components. Components support basic commands like startComponent, stopComponent, suspendComponent & resumeComponent. I am using jmx mgmt interface to call start, stop, suspend & resume commands. I am also using timer task in my components. My component start purgeTimerTask during startComponent call.
    I want purgeTimerTask to wait when my component is suspended & purgeTimerTask should be notify() when my component get resumed.
    Following is the implementation of suspendComponent() method.
    public void suspendComponent()
            try
                if (null != purgeTimerTask)
                    synchronized (purgeTimerTask)
                           purgeTimerTask.wait();
            catch (InterruptedException e)
                logError("PurgeComponent.suspendComponent() - exception: " + e);
        }Calling suspendComponent() method from JMX mgmt interface, control is not coming out of suspendComponent() method.
    I am not able to understand what is the cause of not coming out of suspendComponent() method.
    I have implemented resumeComponent() method where i am calling purgeTimerTask.notify() to reactivate the timer task.
    Can any one guide me here how can i resolve this issue?
    Thanks & regards,
    Pawan Modi

    PawanModi wrote:
    Hi, Ok you are right. After debugging i found that my current (application) thread is waiting at following statement.
    purgerTimerTask.wait();And not coming out of this statement.
    It won't come out until some other thread calls purgerTimerTask.notify().
    But this isn't a safe way to use wait and notify. You should do something like this:
    [code[
    synchronized(someMonitor) {
    while(suspended) {
    someMontitor.wait();
    And resume like:
    synchronized(someMonitor) {
        suspended = false;
        someMonitor.notifyAll();
    }

  • Trying to wrap my head around synchronized, wait, notify

    Hi There,
    I've been researching on how to make my midlet repeat cpu-intensive tasks for long periods of time. I found that if I put the big jobs in separate threads, that works fine. However, I'm at a point now where I need my "worker threads" to be able to do a big job, check to see if they need to keep going, then repeat. It seems that synchronized, wait, and notify are the way to do that. But I'm new to this concept.
    Apparently you can only use synchronized to create a spinlock between objects. So I guess that I need to define a new class, that starts its own thread, and has a method inside that thread that is synchronized?
    If that is true, then can my midlet call notify() on that? How does my midlet become a monitor?
    What does notify really do? Does it make the thread synch up state with the midlet globals? How can I get updated information to the thread?
    These things will help me get started.
    Thanks,
    theotherldso

    I answered my own question. I solved the problem by creating my own runnable class with some methods to control the thread. It works great, it's kind of like having my own main() that is controlled from my midlet.

  • Thread question wait() notify()

    The wait method must be called inside a try block because it declares that it throws an InterruptedException. Under what condition will it actually throw that exception and print "Caught InterruptedException" in the code below?
    public synchronized void amethod()
    try{
    wait();
    }catch(InterruptedException ie)
    System.out.println("Caught InterruptedException");
    I tried similar code and when the thread was notified and continued no exception was thrown.
    Thanks,
    Darrin

    The InterruptedException will be thrown if some other thread calls the interrupt method on the thread that is waiting.

  • Strange behaviour with 'Wait' activities using BPEL 10.1.3

    Hi All,
    We have just migrated from BPEL 10.1.2 to BPEL 10.1.3 and now we have a weird problem with the Wait activity.
    We have a process with several wait activities; end the problem is that the last wait activity is hanging (it should wait for 5 seconds, but it never ends waiting).
    After removing the last wait, this problem arises at the previous wait activity.
    Therefore I made a seperate BPEL process with only some wait activities with several forms (using hardcoded waittime and using waittime from variables, but those wait times were working correctly).
    Note: I have programmed a lot of processes already within BPEL, so it is NOT a beginners fault.
    Does someone have an idea what is happening here.

    Fixed.
    Quote from a response to a ticket.
    You may not have enough timer expirationAgent threads...
    Try the following...
    1. Stop your application server
    2 Take a backup copy of the following file:
    <Oracle_Home>\bpel\domains\<domain-name>\config\resources-quartz.properties
    3 Edit the original resources-quartz.properties
    It contains the following property : com.oracle.bpel.expirationAgent.threadCount
    It's value is set to 10 by default.
    Increase the value, for example: 200.
    4 Restart the application server

  • How to wait for a Process to complete without using wait,notify methods

    I have created a new Process using run.exec() method using a cmdline String array in the format "java, class name, 4 command line arguments" to be passed to the main method of that class. But I have a maximum limit of the no. of processes to be created e.g. 5. So whenever I create a process, I use a static semaphore class to decrease the count, and increase it again when the process ends; so when the 6th process wants to start it will be suspended until another process is complete. My problem is how do I communicate to the calling class that the process has ended. I don't want to create any threads as that will defeat the purpose of creating separate processes. I have tried Process.waitFor() method but it doesn't work.

    you could add a iamfinished method to the class where you store the counter and thread calls it if it is finished.

  • How to notify the waiting queue with first-in-first-out?

    Could anyone know
    how to notify the waiting queue with first-in-first-out?
    I dont want to notify the waiting queue randomly!
    thanks~

    i assume you are referring to wait "queue" of threads waiting to be notified. while you can do this with some effort on your own part (it's not trivial), depending on what type of guarantees you want, you could use a ReentrantLock with the "fair" policy. it tries to be FIFO but doesn't guarantee it. if you need stronger guarantees, then you will have to code it yourself.
    note, that many of the reasons for using wait/notify explicitly are now handled with some of the concurrent utilities like BlockingQueue, so you may not need to code your own wait/notify logic.

  • Why notify/notifyAll method doesn't resume the waiting thread quickly?????

    I am currently working on a socket based IM server, I get messages from multiple clients simultaneously and put them into queues, for each queue in my server I have a separate listener running in a thread, as soon as a packet comes in the queue (from any client) it��s related thread is notified to get that packet from thread and process it.
    Here I am using wait/notify blocking mechanism to control loop in my listener thread. My logic works like this
    1)     When Listener thread starts it calls the synchronized getNextPacket method on that queue if the queue has any packet (i.e. it��s length is greater then zero) then it will remove that packet from the underlying vector (NOTE: I am using Vector to contain packets) and return that packet to listener thread, else if queue doesn��t have any packet (i.e. its size is zero) then I will call wait() method which causes the listener thread to wait.
    2)     Now when any client adds some packet in that queue using synchronized addPacket( ) method I first add that packet in the underlying vector and then call notify()/notifyAll() to awake that listener thread, which again calls the getNextPacket() method and this cycle continuous like this.
    So multiple threads (clients) are adding data in the queue using synchronized method, only one listener thread is getting data from that queue using a synchronized method again �� .
    This approach works fine but sometimes I have noticed that the listener thread doesn��t resume just after notiy() / notifyAll() has been called , sometimes it resumes after a long time sometimes it even don��t resume (after waiting a long time I assumed this).
    Solutions I tried
    1)     I did set the listener Thread��s priority to Maximum but facing same problem again.
    For better understanding I am also sending you the code for my queue class and it��s listener thread.
    CODE OF QUEUE CLASS
    import java.util.Vector;
    import org.apache.log4j.Logger;
    import com.tcm.unicorn.server.UnicornCustomeObject;
    * @author sajjad.paracha
    public class UIMPCommandsQueue {
         private static final Logger logger=Logger.getLogger(UIMPCommandsQueue.class);
          * Contains all the packets from clients
         private Vector <UnicornCustomeObject> unicornCustomeObjectQueue = new Vector<UnicornCustomeObject>();
         private UIMPCommandsQueue(){
         private static UIMPCommandsQueue uIMPCommandsQueue = null;
         public static UIMPCommandsQueue getInstance(){
              synchronized(UIMPCommandsQueue.class){
                   if(uIMPCommandsQueue!=null){
                        return uIMPCommandsQueue;
                   }else
                        return uIMPCommandsQueue = new UIMPCommandsQueue();
          * Adds a new command
          * @param unicornCustomeObject
         public synchronized void addCommandPakcet(UnicornCustomeObject unicornCustomeObject){
              logger.debug("[[[[[[[[[[[[[[[[[[[[[[[[[[   Going to add a packet in queue  no "+unicornCustomeObject.getClientSession().getRequestQueueNo());
              unicornCustomeObjectQueue.add(unicornCustomeObject);
              //** Notify the Listener (RequestProcessor) Thread that a new packet has been arrived in the queue
              //** So it now can again start it's processing
              notifyAll();
          * Removes an object from queue whose processing has been started or completed
          * @param unicornCustomeObject
          * @return
         private boolean removeCommandPacket(UnicornCustomeObject unicornCustomeObject){
              return unicornCustomeObjectQueue.remove(unicornCustomeObject);
          * <p> If no packet is available in queue it retuns null value
          *     otherwise returns an object from that queue
          * <p>
          * @return unicornCustomeObject
         public synchronized UnicornCustomeObject getNextCommandPacket(){
              if(unicornCustomeObjectQueue.size()>0){
                   UnicornCustomeObject unicornCustomeObject = unicornCustomeObjectQueue.get(0);
                   logger.debug("[[[[[[[[[[[[[[[[[[[[[[[[[[   Got a packet from queue no  "+unicornCustomeObject.getClientSession().getRequestQueueNo());
                   logger.debug("[[[[[[[[[[[[[[[[[[[[[[[[[[   Going to remove a packet from queue no  "+unicornCustomeObject.getClientSession().getRequestQueueNo());
                   removeCommandPacket(unicornCustomeObject);
                   return unicornCustomeObject;
              }else{
                   try {
                        //** Force the Listener (RequestProcessor) Thread to wait for notification
                        //** This Thread will be only notified if a new command packet has been arrived(added) in the
                        //** Queue i.e in addCommandPacket Method
                        wait();
                   } catch (InterruptedException e) {
                        logger.error("",e);
                   return null;
    CODE OF LISTENER CLASS
    import org.apache.log4j.Logger;
    import com.tcm.unicorn.server.UnicornCustomeObject;
    public class RequestProcessor implements Runnable {
          * will listen on Request queue for any new massages
         public void run() {
                   //** get an instance of RequestQueue before the loop  
                   UIMPCommandsQueue requestQueue= UIMPCommandsQueue.getInstance();
                   while(true){
                        try{
                             //**call the blocking method getNextCommandPacket()     
                             UnicornCustomeObject unicornCustomeObject= requestQueue.getNextCommandPacket();
                             if(unicornCustomeObject!=null){
                                  System.out.println("Got a pcket will process it now.......");                    
                        }catch(Exception exp){
                             exp.printStackTrace();
    Can anybody please tell me where I am doing something wrong and whats the best way to get rid of this situation .
    Thanks in advance
    Message was edited by:
    meetsaju

    Another question !
    in my previous programe i have seen a starange behavior , my processor thread sometimes processes the later message before the message came before that in queue here is an output of my debug statements
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 10
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 11
    INFO :03 May 2007 11:21:17,>>>>>>>>>>>>>>>>>>>>>>>>requestProcessorThread is in block state
    INFO :03 May 2007 11:21:17,>>>>>>>>>>>>>>>>>>>>>>>>requestProcessorThread is in block state
    INFO :03 May 2007 11:21:17,>>>>>>>>>>>>>>>>>>>>>>>>requestProcessorThread is in block state
    INFO :03 May 2007 11:21:17,>>>>>>>>>>>>>>>>>>>>>>>>requestProcessorThread is in block state
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 30
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 13
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 0
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 12
    INFO :03 May 2007 11:21:17,>>>>>>>>>>>>>>>>>>>>>>>>requestProcessorThread is in block state
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 20
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 40
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 31
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 14
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 15
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 32
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 33
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 16
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 34
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 17
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 35
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 18
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 36
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 19
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 37
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 41
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 38
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 39
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 42
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 43
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 21
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 44
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 22
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 45
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 23
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 46
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 24
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 47
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 25
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 26
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 49
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 48
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 27
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 28
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 1
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 2 look at the lines
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 49
    INFO :03 May 2007 11:21:17,[[[[[[[[[[[[[[[[[[[[[[[process the packet no 48
    as for as i know it shouldnt be the case as we are using a FIFO queue here....just querious how it is possible that a later message is taken from a FIFO queue.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Notify/Wait or Observable/Observer?

    Hi,
    I have one thread process the data and store the result in a data object. Several threads access the data object to display.
    Which one to use:
    1) Have the processing thread notify the display threads when it's done? Using thread wait()/notify()?
    2) Have the data object be the observable, and the dislay threads be the observers? Using the observable/observer concept?
    Thanks

    How exactly would you code the wait/notify method calls? I had dynamic data that was used to update the data models for a JList and a JTable, and found it difficult to notify the models correctly, after the data changed.
    Somehow the object has to "post" the fact that it has changed, a job for Observer/Observable. The Thread tutorial and the various Swing tutorials don't quite describe this in a way I understand. Can somebody give an example of how to use notify/wait in this sort of situation? Thanks.

  • 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

  • Apple TV + Airplay in Van Working

    This is probably old news but I thought I would post my success with getting Apple TV and Airplay working in my 2014 Grand Caravan. When I searched for how to do this I didn't come up with much. There was a few youtube videos that talked about hookin

  • Threads listed using kill -3 does not contain all threads via ps -auxww

    Hello We are currently experiencing a problem running ServletExec (java Servlet container) where a process starts hogging the CPU. We end up having to restart the program. As a Java developer, in these situations you tend to issue "kill -3 <pid>" com

  • BPM : Receiver Determination Step

    Hi, I was wondering why we need a Reciever determination step since on send step xi automatically find that there are multiple receiver and sends them accordingly to the different system as per reciever agreement. Is it that the receiver determinatio

  • Why do I get an error message when I try installing the free trial for Adobe Illustrator

    I'm trying to install the free trial for Adobe Illustrator and keep getting this message: The address wasn't understood Firefox doesn't know how to open this address, because one of the following protocols (aam) isn't associated with any program or i

  • Does the Travel Kit work with the Mac mini?

    Hey guys, I wanted to know if the Travel Kit that Apple sells would be compatible with the Mac Mini. I am thinking of buying one in the US for money's sake, and I live in the UK. I just wanted to make sure that if I did get it, it wouldnt be a waste