<p>If one Googles for "difference between <code>notify()</code> and <code>notifyAll()</code>" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in <code>notify()</code> and all in <code>notifyAll()</code>.</p>

<p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.</p>

<p>What's the <strong>useful</strong> difference between <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29" rel="noreferrer">notify()</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29" rel="noreferrer">notifyAll()</a> then? Am I missing something?</p>

[{'answer_id': 37038, 'author': 'Spoike', 'author_id': 3713, 'author_profile': 'https://Stackoverflow.com/users/3713', 'pm_score': 2, 'selected': False, 'text': '<p><code>notify()</code> will wake up one thread while <code>notifyAll()</code> will wake up all. As far as I know there is no middle ground. But if you are not sure what <code>notify()</code> will do to your threads, use <code>notifyAll()</code>. Works like a charm everytime.</p>\n'}, {'answer_id': 37045, 'author': 'andyuk', 'author_id': 2108, 'author_profile': 'https://Stackoverflow.com/users/2108', 'pm_score': 4, 'selected': False, 'text': '<p>I think it depends on how resources are produced and consumed. If 5 work objects are available at once and you have 5 consumer objects, it would make sense to wake up all threads using notifyAll() so each one can process 1 work object.</p>\n\n<p>If you have just one work object available, what is the point in waking up all consumer objects to race for that one object? The first one checking for available work will get it and all other threads will check and find they have nothing to do.</p>\n\n<p>I found a <a href="http://www.javamex.com/tutorials/notifyall.shtml" rel="noreferrer">great explanation here</a>. In short: </p>\n\n<blockquote>\n  <p>The notify() method is generally used\n  for <strong>resource pools</strong>, where there\n  are an arbitrary number of "consumers"\n  or "workers" that take resources, but\n  when a resource is added to the pool,\n  only one of the waiting consumers or\n  workers can deal with it. The\n  notifyAll() method is actually used in\n  most other cases. Strictly, it is\n  required to notify waiters of a\n  condition that could allow multiple\n  waiters to proceed. But this is often\n  difficult to know. So as a general\n  rule, <strong>if you have no particular\n  logic for using notify(), then you\n  should probably use notifyAll()</strong>,\n  because it is often difficult to know\n  exactly what threads will be waiting\n  on a particular object and why.</p>\n</blockquote>\n'}, {'answer_id': 37046, 'author': 'Liedman', 'author_id': 890, 'author_profile': 'https://Stackoverflow.com/users/890', 'pm_score': 9, 'selected': True, 'text': "<blockquote>\n  <p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.</p>\n</blockquote>\n\n<p>That is not correct.  <code>o.notifyAll()</code> wakes <em>all</em> of the threads that are blocked in <code>o.wait()</code> calls.  The threads are only allowed to return from <code>o.wait()</code> one-by-one, but they each <em>will</em> get their turn.</p>\n\n<hr>\n\n<p>Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?</p>\n\n<p>In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use <b>notifyAll()</b> to wake up all waiting threads at the same time.</p>\n\n<p>Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use <b>notify()</b>. Properly implemented, you <i>could</i> use <b>notifyAll()</b> in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.</p>\n\n<hr>\n\n<p>In many cases, the code to await a condition will be written as a loop:</p>\n\n<pre><code>synchronized(o) {\n    while (! IsConditionTrue()) {\n        o.wait();\n    }\n    DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();\n}\n</code></pre>\n\n<p>That way, if an <code>o.notifyAll()</code> call wakes more than one waiting thread, and the first one to return from the <code>o.wait()</code> makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.</p>\n"}, {'answer_id': 37050, 'author': 'David Crow', 'author_id': 2783, 'author_profile': 'https://Stackoverflow.com/users/2783', 'pm_score': 6, 'selected': False, 'text': "<p>Useful differences:</p>\n\n<ul>\n<li><p>Use <strong>notify()</strong> if all your waiting threads are interchangeable (the order they wake up doesn't matter), or if you only ever have one waiting thread. A common example is a thread pool used to execute jobs from a queue--when a job is added, one of threads is notified to wake up, execute the next job and go back to sleep.</p></li>\n<li><p>Use <strong>notifyAll()</strong> for other cases where the waiting threads may have different purposes and should be able to run concurrently. An example is a maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource.</p></li>\n</ul>\n"}, {'answer_id': 37058, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>All the above answers are correct, as far as I can tell, so I'm going to tell you something else. For production code you really should use the classes in java.util.concurrent. There is very little they cannot do for you, in the area of concurrency in java.</p>\n"}, {'answer_id': 41788, 'author': 'Steve McLeod', 'author_id': 2959, 'author_profile': 'https://Stackoverflow.com/users/2959', 'pm_score': 3, 'selected': False, 'text': '<p>From Joshua Bloch, the Java Guru himself in Effective Java 2nd edition:</p>\n\n<p>"Item 69: Prefer concurrency utilities to wait and notify".</p>\n'}, {'answer_id': 1006498, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Note that with concurrency utilities you also have the choice between <code>signal()</code> and <code>signalAll()</code> as these methods are called there.  So the question remains valid even with <code>java.util.concurrent</code>.</p>\n\n<p>Doug Lea brings up an interesting point in his <a href="http://www.informit.com/store/product.aspx?isbn=0201310090" rel="noreferrer">famous book</a>: if a <code>notify()</code> and <code>Thread.interrupt()</code> happen at the same time, the notify might actually get lost.  If this can happen and has dramatic implications <code>notifyAll()</code> is a safer choice even though you pay the price of overhead (waking too many threads most of the time).</p>\n'}, {'answer_id': 1899610, 'author': 'Abhay Bansal', 'author_id': 231084, 'author_profile': 'https://Stackoverflow.com/users/231084', 'pm_score': -1, 'selected': False, 'text': "<p>Waking up all does not make much significance here. \nwait notify and notifyall, all these are put after owning the object's monitor. If a thread is in the waiting stage and notify is called, this thread will take up the lock and no other thread at that point can take up that lock. So concurrent access can not take place at all. As far as i know any call to wait notify and notifyall can be made only after taking the lock on the object. Correct me if i am wrong.</p>\n"}, {'answer_id': 2879412, 'author': 'Erik', 'author_id': 346719, 'author_profile': 'https://Stackoverflow.com/users/346719', 'pm_score': 3, 'selected': False, 'text': '<p>Here is an example. Run it. Then change one of the notifyAll() to notify() and see what happens.</p>\n\n<p><strong>ProducerConsumerExample class</strong></p>\n\n<pre><code>public class ProducerConsumerExample {\n\n    private static boolean Even = true;\n    private static boolean Odd = false;\n\n    public static void main(String[] args) {\n        Dropbox dropbox = new Dropbox();\n        (new Thread(new Consumer(Even, dropbox))).start();\n        (new Thread(new Consumer(Odd, dropbox))).start();\n        (new Thread(new Producer(dropbox))).start();\n    }\n}\n</code></pre>\n\n<p><strong>Dropbox class</strong></p>\n\n<pre><code>public class Dropbox {\n\n    private int number;\n    private boolean empty = true;\n    private boolean evenNumber = false;\n\n    public synchronized int take(final boolean even) {\n        while (empty || evenNumber != even) {\n            try {\n                System.out.format("%s is waiting ... %n", even ? "Even" : "Odd");\n                wait();\n            } catch (InterruptedException e) { }\n        }\n        System.out.format("%s took %d.%n", even ? "Even" : "Odd", number);\n        empty = true;\n        notifyAll();\n\n        return number;\n    }\n\n    public synchronized void put(int number) {\n        while (!empty) {\n            try {\n                System.out.println("Producer is waiting ...");\n                wait();\n            } catch (InterruptedException e) { }\n        }\n        this.number = number;\n        evenNumber = number % 2 == 0;\n        System.out.format("Producer put %d.%n", number);\n        empty = false;\n        notifyAll();\n    }\n}\n</code></pre>\n\n<p><strong>Consumer class</strong></p>\n\n<pre><code>import java.util.Random;\n\npublic class Consumer implements Runnable {\n\n    private final Dropbox dropbox;\n    private final boolean even;\n\n    public Consumer(boolean even, Dropbox dropbox) {\n        this.even = even;\n        this.dropbox = dropbox;\n    }\n\n    public void run() {\n        Random random = new Random();\n        while (true) {\n            dropbox.take(even);\n            try {\n                Thread.sleep(random.nextInt(100));\n            } catch (InterruptedException e) { }\n        }\n    }\n}\n</code></pre>\n\n<p><strong>Producer class</strong></p>\n\n<pre><code>import java.util.Random;\n\npublic class Producer implements Runnable {\n\n    private Dropbox dropbox;\n\n    public Producer(Dropbox dropbox) {\n        this.dropbox = dropbox;\n    }\n\n    public void run() {\n        Random random = new Random();\n        while (true) {\n            int number = random.nextInt(10);\n            try {\n                Thread.sleep(random.nextInt(100));\n                dropbox.put(number);\n            } catch (InterruptedException e) { }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 3186336, 'author': 'xagyg', 'author_id': 384464, 'author_profile': 'https://Stackoverflow.com/users/384464', 'pm_score': 9, 'selected': False, 'text': "<p>Clearly, <code>notify</code> wakes (any) one thread in the wait set, <code>notifyAll</code> wakes all threads in the waiting set. The following discussion should clear up any doubts. <code>notifyAll</code> should be used most of the time. If you are not sure which to use, then use <code>notifyAll</code>.Please see explanation that follows.</p>\n\n<p>Read very carefully and understand. Please send me an email if you have any questions.</p>\n\n<p>Look at producer/consumer (assumption is a ProducerConsumer class with two methods). IT IS BROKEN (because it uses <code>notify</code>) - yes it MAY work - even most of the time, but it may also cause deadlock - we will see why:</p>\n\n<pre><code>public synchronized void put(Object o) {\n    while (buf.size()==MAX_SIZE) {\n        wait(); // called if the buffer is full (try/catch removed for brevity)\n    }\n    buf.add(o);\n    notify(); // called in case there are any getters or putters waiting\n}\n\npublic synchronized Object get() {\n    // Y: this is where C2 tries to acquire the lock (i.e. at the beginning of the method)\n    while (buf.size()==0) {\n        wait(); // called if the buffer is empty (try/catch removed for brevity)\n        // X: this is where C1 tries to re-acquire the lock (see below)\n    }\n    Object o = buf.remove(0);\n    notify(); // called if there are any getters or putters waiting\n    return o;\n}\n</code></pre>\n\n<p>FIRSTLY,</p>\n\n<p><strong>Why do we need a while loop surrounding the wait?</strong></p>\n\n<p>We need a <code>while</code> loop in case we get this situation:</p>\n\n<p>Consumer 1 (C1) enter the synchronized block and the buffer is empty, so C1 is put in the wait set (via the <code>wait</code> call). Consumer 2 (C2) is about to enter the synchronized method (at point Y above), but Producer P1 puts an object in the buffer, and subsequently calls <code>notify</code>. The only waiting thread is C1, so it is woken and now attempts to re-acquire the object lock at point X (above).</p>\n\n<p>Now C1 and C2 are attempting to acquire the synchronization lock. One of them (nondeterministically) is chosen and enters the method, the other is blocked (not waiting - but blocked, trying to acquire the lock on the method). Let's say C2 gets the lock first. C1 is still blocking (trying to acquire the lock at X). C2 completes the method and releases the lock. Now, C1 acquires the lock. Guess what, lucky we have a <code>while</code> loop, because, C1 performs the loop check (guard) and is prevented from removing a non-existent element from the buffer (C2 already got it!). If we didn't have a <code>while</code>, we would get an <code>IndexArrayOutOfBoundsException</code> as C1 tries to remove the first element from the buffer!</p>\n\n<p>NOW,</p>\n\n<p><strong>Ok, now why do we need notifyAll?</strong></p>\n\n<p>In the producer/consumer example above it looks like we can get away with <code>notify</code>. It seems this way, because we can prove that the guards on the <em>wait</em> loops for producer and consumer are mutually exclusive. That is, it looks like we cannot have a thread waiting in the <code>put</code> method as well as the <code>get</code> method, because, for that to be true, then the following would have to be true:</p>\n\n<p><code>buf.size() == 0 AND buf.size() == MAX_SIZE</code> (assume MAX_SIZE is not 0)</p>\n\n<p>HOWEVER, this is not good enough, we NEED to use <code>notifyAll</code>. Let's see why ...</p>\n\n<p>Assume we have a buffer of size 1 (to make the example easy to follow). The following steps lead us to deadlock. Note that ANYTIME a thread is woken with notify, it can be non-deterministically selected by the JVM - that is any waiting thread can be woken. Also note that when multiple threads are blocking on entry to a method (i.e. trying to acquire a lock), the order of acquisition can be non-deterministic. Remember also that a thread can only be in one of the methods at any one time - the synchronized methods allow only one thread to be executing (i.e. holding the lock of) any (synchronized) methods in the class. If the following sequence of events occurs - deadlock results:</p>\n\n<p><strong>STEP 1:</strong><BR>\n- P1 puts 1 char into the buffer</p>\n\n<p><strong>STEP 2:</strong><BR>\n- P2 attempts <code>put</code> - checks wait loop - already a char - waits</p>\n\n<p><strong>STEP 3:</strong><BR>\n- P3 attempts <code>put</code> - checks wait loop - already a char - waits</p>\n\n<p><strong>STEP 4:</strong><BR>\n- C1 attempts to get 1 char <BR>\n- C2 attempts to get 1 char - blocks on entry to the <code>get</code> method<BR>\n- C3 attempts to get 1 char - blocks on entry to the <code>get</code> method</p>\n\n<p><strong>STEP 5:</strong><BR>\n- C1 is executing the <code>get</code> method - gets the char, calls <code>notify</code>, exits method<BR>\n- The <code>notify</code> wakes up P2<BR>\n- BUT, C2 enters method before P2 can (P2 must reacquire the lock), so P2 blocks on entry to the <code>put</code> method<BR>\n- C2 checks wait loop, no more chars in buffer, so waits<BR>\n- C3 enters method after C2, but before P2, checks wait loop, no more chars in buffer, so waits</p>\n\n<p><strong>STEP 6:</strong><BR>\n- NOW: there is P3, C2, and C3 waiting!<BR>\n- Finally P2 acquires the lock, puts a char in the buffer, calls notify, exits method</p>\n\n<p><strong>STEP 7:</strong><BR>\n- P2's notification wakes P3 (remember any thread can be woken)<BR>\n- P3 checks the wait loop condition, there is already a char in the buffer, so waits.<BR>\n- NO MORE THREADS TO CALL NOTIFY and THREE THREADS PERMANENTLY SUSPENDED!</p>\n\n<p>SOLUTION: Replace <code>notify</code> with <code>notifyAll</code> in the producer/consumer code (above).</p>\n"}, {'answer_id': 8390277, 'author': 'Kshitij Banerjee', 'author_id': 985306, 'author_profile': 'https://Stackoverflow.com/users/985306', 'pm_score': 0, 'selected': False, 'text': '<p><code>notify()</code> wakes up the first thread that called <code>wait()</code> on the same object.</p>\n\n<p><code>notifyAll()</code> wakes up all the threads that called <code>wait()</code> on the same object.</p>\n\n<p>The highest priority thread will run first.</p>\n'}, {'answer_id': 9880331, 'author': 'alxlevin', 'author_id': 1294054, 'author_profile': 'https://Stackoverflow.com/users/1294054', 'pm_score': 2, 'selected': False, 'text': '<p>Take a look at the code posted by @xagyg.  </p>\n\n<p>Suppose two different threads are waiting for two different conditions:<br>\nThe <strong>first thread</strong> is waiting for <code>buf.size() != MAX_SIZE</code>, and the <strong>second thread</strong> is waiting for <code>buf.size() != 0</code>.  </p>\n\n<p>Suppose at some point <code>buf.size()</code> <strong>is not equal to 0</strong>. JVM calls <code>notify()</code> instead of <code>notifyAll()</code>, and the first thread is notified (not the second one).   </p>\n\n<p>The first thread is woken up, checks for <code>buf.size()</code> which might return <code>MAX_SIZE</code>, and goes back to waiting. The second thread is not woken up, continues to wait and does not call <code>get()</code>.</p>\n'}, {'answer_id': 12439274, 'author': 'NickV', 'author_id': 1617892, 'author_profile': 'https://Stackoverflow.com/users/1617892', 'pm_score': 3, 'selected': False, 'text': '<p>I am very surprised that no one mentioned the infamous "lost wakeup" problem (google it).</p>\n\n<p>Basically:</p>\n\n<ol>\n<li>if you have multiple threads waiting on a same condition and, </li>\n<li>multiple threads that can make you transition from state A to state B and,</li>\n<li>multiple threads that can make you transition from state B to state A (usually the same threads as in 1.) and,</li>\n<li>transitioning from state A to B should notify threads in 1.  </li>\n</ol>\n\n<p>THEN you should use notifyAll unless you have provable guarantees that lost wakeups are impossible.</p>\n\n<p>A common example is a concurrent FIFO queue where:\nmultiple enqueuers (1. and 3. above) can transition your queue from empty to non-empty \nmultiple dequeuers (2. above) can wait for the condition "the queue is not empty"\nempty -> non-empty should notify dequeuers</p>\n\n<p>You can easily write an interleaving of operations in which, starting from an empty queue, 2 enqueuers and 2 dequeuers interact and 1 enqueuer will remain sleeping.</p>\n\n<p>This is a problem arguably comparable with the deadlock problem.</p>\n'}, {'answer_id': 17158435, 'author': 'Alexander Ryzhov', 'author_id': 1713695, 'author_profile': 'https://Stackoverflow.com/users/1713695', 'pm_score': 2, 'selected': False, 'text': "<p><code>notify()</code> lets you write more efficient code than <code>notifyAll()</code>.</p>\n\n<p>Consider the following piece of code that's executed from multiple parallel threads:\n</p>\n\n<pre><code>synchronized(this) {\n    while(busy) // a loop is necessary here\n        wait();\n    busy = true;\n}\n...\nsynchronized(this) {\n    busy = false;\n    notifyAll();\n}\n</code></pre>\n\n<p>It can be made more efficient by using <code>notify()</code>:\n</p>\n\n<pre><code>synchronized(this) {\n    if(busy)   // replaced the loop with a condition which is evaluated only once\n        wait();\n    busy = true;\n}\n...\nsynchronized(this) {\n    busy = false;\n    notify();\n}\n</code></pre>\n\n<p>In the case if you have a large number of threads, or if the wait loop condition is costly to evaluate, <code>notify()</code> will be significantly faster than <code>notifyAll()</code>. For example, if you have 1000 threads then 999 threads will be awakened and evaluated after the first <code>notifyAll()</code>, then 998, then 997, and so on. On the contrary, with the <code>notify()</code> solution, only one thread will be awakened. </p>\n\n<p>Use <code>notifyAll()</code> when you need to choose which thread will do the work next:\n</p>\n\n<pre><code>synchronized(this) {\n    while(idx != last+1)  // wait until it's my turn\n        wait();\n}\n...\nsynchronized(this) {\n    last = idx;\n    notifyAll();\n}\n</code></pre>\n\n<p>Finally, it's important to understand that in case of <code>notifyAll()</code>, the code inside <code>synchronized</code> blocks that have been awakened will be executed sequentially, not all at once. Let's say there are three threads waiting in the above example, and the fourth thread calls <code>notifyAll()</code>. All three threads will be awakened but only one will start execution and check the condition of the <code>while</code> loop. If the condition is <code>true</code>, it will call <code>wait()</code> again, and only then the second thread will start executing and will check its <code>while</code> loop condition, and so on.</p>\n"}, {'answer_id': 17287218, 'author': 'Steve', 'author_id': 489457, 'author_profile': 'https://Stackoverflow.com/users/489457', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s a simpler explanation:</p>\n\n<p>You\'re correct that whether you use notify() or notifyAll(), the immediate result is that exactly one other thread will acquire the monitor and begin executing. (Assuming some threads were in fact blocked on wait() for this object, other unrelated threads aren\'t soaking up all available cores, etc.) The impact comes later.</p>\n\n<p>Suppose thread A, B, and C were waiting on this object, and thread A gets the monitor. The difference lies in what happens once A releases the monitor. If you used notify(), then B and C are still blocked in wait(): they are not waiting on the monitor, they are waiting to be notified. When A releases the monitor, B and C will still be sitting there, waiting for a notify().</p>\n\n<p>If you used notifyAll(), then B and C have both advanced past the "wait for notification" state and are both waiting to acquire the monitor. When A releases the monitor, either B or C will acquire it (assuming no other threads are competing for that monitor) and begin executing.</p>\n'}, {'answer_id': 18650599, 'author': 'AKS', 'author_id': 1669747, 'author_profile': 'https://Stackoverflow.com/users/1669747', 'pm_score': 2, 'selected': False, 'text': "<p>I would like to mention what is explained in Java Concurrency in Practice:</p>\n\n<p><strong>First point, whether Notify or NotifyAll?</strong></p>\n\n<pre><code>It will be NotifyAll, and reason is that it will save from signall hijacking.\n</code></pre>\n\n<blockquote>\n  <p>If two threads A and B are waiting on different condition predicates\n  of same condition queue and notify is called, then it is upto JVM to\n  which thread JVM will notify.</p>\n  \n  <p>Now if notify was meant for thread A and JVM notified thread B, then\n  thread B will wake up and see that this notification is not useful so\n  it will wait again. And Thread A will never come to know about this\n  missed signal and someone hijacked it's notification.</p>\n  \n  <p>So, calling notifyAll will resolve this issue, but again it will have\n  performance impact as it will notify all threads and all threads will\n  compete for same lock and it will involve context switch and hence\n  load on CPU. But we should care about performance only if it is\n  behaving correctly, if it's behavior itself is not correct then\n  performance is of no use.</p>\n</blockquote>\n\n<p><strong>This problem can be solved with using Condition object of explicit locking Lock, provided in jdk 5, as it provides different wait for each condition predicate. Here it will behave correctly and there will not be performance issue as it will call signal and make sure that only one thread is waiting for that condition</strong></p>\n"}, {'answer_id': 24894963, 'author': 'Saurabh', 'author_id': 2377539, 'author_profile': 'https://Stackoverflow.com/users/2377539', 'pm_score': 1, 'selected': False, 'text': '<p>notify will notify only one thread which are in waiting state, while notify all will notify all the threads in the waiting state now all the notified threads and all the blocked threads are eligible for the lock, out of which only one will get the lock and all others (including those who are in waiting state earlier) will be in blocked state.</p>\n'}, {'answer_id': 33066887, 'author': 'KingCode', 'author_id': 401598, 'author_profile': 'https://Stackoverflow.com/users/401598', 'pm_score': 1, 'selected': False, 'text': '<p>To summarize the excellent detailed explanations above, and in the simplest way I can think of, this is due to the limitations of the JVM built-in monitor, which 1) is acquired on the entire synchronization unit (block or object) and 2) does not discriminate about the specific condition being waited/notified on/about. </p>\n\n<p>This means that if multiple threads are waiting on different conditions and notify() is used, the selected thread may not be the one which would make progress on the newly fulfilled condition - causing that thread (and other currently still waiting threads which would be able to fulfill the condition, etc..) not to be able to make progress, and eventually starvation or program hangup. </p>\n\n<p>In contrast, notifyAll() enables all waiting threads to eventually re-acquire the lock and check for their respective condition, thereby eventually allowing progress to be made. </p>\n\n<p>So notify() can be used safely only if any waiting thread is guaranteed to allow progress to be made should it be selected, which in general is satisfied when all threads within the same monitor check for only one and the same condition - a fairly rare case in real world applications. </p>\n'}, {'answer_id': 33329002, 'author': 'ansd', 'author_id': 4961112, 'author_profile': 'https://Stackoverflow.com/users/4961112', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Short summary:</strong></p>\n\n<p>Always prefer <strong>notifyAll()</strong> over <strong>notify()</strong> unless you have a massively parallel application where a large number of threads all do the same thing.</p>\n\n<p><strong>Explanation:</strong></p>\n\n<blockquote>\n  <p><strong>notify()</strong> [...] wakes up a single\n  thread. Because <strong>notify()</strong> doesn\'t allow you to specify the thread that is\n  woken up, it is useful only in massively parallel applications — that\n  is, programs with a large number of threads, all doing similar chores.\n  In such an application, you don\'t care which thread gets woken up.</p>\n</blockquote>\n\n<p>source: <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html" rel="noreferrer">https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html</a></p>\n\n<p>Compare <strong>notify()</strong> with <strong>notifyAll()</strong> in the above described situation: a massively parallel application where threads are doing the same thing. If you call <strong>notifyAll()</strong> in that case, <strong>notifyAll()</strong> will induce the waking up (i.e. scheduling) of a huge number of threads, many of them unnecessarily (since only one thread can actually proceed, namely the thread which will be granted the monitor for the object <strong>wait()</strong>, <strong>notify()</strong>, or <strong>notifyAll()</strong> was called on), therefore wasting computing resources.</p>\n\n<p>Thus, if you don\'t have an application where a huge number of threads do the same thing concurrently, prefer <strong>notifyAll()</strong> over <strong>notify()</strong>. Why? Because, as other users have already answered in this forum, <strong>notify()</strong> </p>\n\n<blockquote>\n  <p>wakes up a single thread that is waiting on this object\'s monitor. [...] The\n  choice is <em>arbitrary</em> and occurs at the discretion of the\n  implementation.</p>\n</blockquote>\n\n<p>source: Java SE8 API (<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--" rel="noreferrer">https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--</a>)</p>\n\n<p>Imagine you have a producer consumer application where consumers are ready (i.e. <strong>wait()</strong> ing) to consume, producers are ready (i.e. <strong>wait()</strong> ing) to produce and the queue of items (to be produced / consumed) is empty. In that case, <strong>notify()</strong> might wake up only consumers and never producers because the choice who is waken up is <em>arbitrary</em>. The producer consumer cycle wouldn\'t make any progress although producers and consumers are ready to produce and consume, respectively. Instead, a consumer is woken up (i.e. leaving the <strong>wait()</strong> status), doesn\'t take an item out of the queue because it\'s empty, and <strong>notify()</strong> s another consumer to proceed.</p>\n\n<p>In contrast, <strong>notifyAll()</strong> awakens both producers and consumers. The choice who is scheduled depends on the scheduler. Of course, depending on the scheduler\'s implementation, the scheduler might also only schedule consumers (e.g. if you assign consumer threads a very high priority). However, the assumption here is that the danger of the scheduler scheduling only consumers is lower than the danger of the JVM only waking up consumers because any reasonably implemented scheduler doesn\'t make just <em>arbitrary</em> decisions. Rather, most scheduler implementations make at least some effort to prevent starvation.</p>\n'}, {'answer_id': 33329952, 'author': 'fireboy91', 'author_id': 4673384, 'author_profile': 'https://Stackoverflow.com/users/4673384', 'pm_score': 2, 'selected': False, 'text': '<p><code>notify()</code> - Selects a random thread from the wait set of the object and puts it in the <code>BLOCKED</code> state. The rest of the threads in the wait set of the object are still in the <code>WAITING</code> state.</p>\n\n<p><code>notifyAll()</code> - Moves all the threads from the wait set of the object to <code>BLOCKED</code> state. After you use <code>notifyAll()</code>, there are no threads remaining in the wait set of the shared object because all of them are now in <code>BLOCKED</code> state and not in <code>WAITING</code> state. </p>\n\n<p><code>BLOCKED</code> - blocked for lock acquisition.\n<code>WAITING</code> - waiting for notify ( or blocked for join completion ).</p>\n'}, {'answer_id': 36777757, 'author': 'Deepak sai', 'author_id': 2477031, 'author_profile': 'https://Stackoverflow.com/users/2477031', 'pm_score': 0, 'selected': False, 'text': '<p>When you call the wait() of the "object"(expecting the object lock is acquired),intern this will release the lock on that object and help\'s the other threads to have lock on this "object", in this scenario there will be more than 1 thread waiting for the "resource/object"(considering the other threads also issued the wait on the same above object and down the way there will be a thread that fill the resource/object and invokes notify/notifyAll). </p>\n\n<p>Here when you issue the notify of the same object(from the same/other side of the process/code),this will release a blocked and waiting single thread (not all the waiting threads  -- this released thread will be picked by JVM Thread Scheduler and all the lock obtaining process on the object is same as regular).</p>\n\n<p>If you have Only one thread that will be sharing/working on this object , it is ok to use the notify() method alone in your wait-notify implementation.</p>\n\n<h2>if you are in situation where more than one thread read\'s and writes on resources/object  based on your business logic,then you should go for notifyAll()</h2>\n\n<p>now i am looking how exactly the jvm is identifying and breaking the waiting thread when we issue notify() on a object ...</p>\n'}, {'answer_id': 41530610, 'author': 'S_R', 'author_id': 1833142, 'author_profile': 'https://Stackoverflow.com/users/1833142', 'pm_score': 3, 'selected': False, 'text': '<p>There are three states for a thread.</p>\n<ol>\n<li>WAIT - The thread is not using any CPU cycle</li>\n<li>BLOCKED - The thread is blocked trying to acquire a monitor. It might still be using the CPU cycles</li>\n<li>RUNNING - The thread is running.</li>\n</ol>\n<p>Now, when a notify() is called, JVM picks one thread and move them to the BLOCKED state and hence to the RUNNING state as there is no competition for the monitor object.</p>\n<p>When a notifyAll() is called, JVM picks all the threads and move all of them to BLOCKED state. All these threads will get the lock of the object on a priority basis. Thread which is able to acquire the monitor first will be able to go to the RUNNING state first and so on.</p>\n'}, {'answer_id': 41910658, 'author': 'jzl106', 'author_id': 2212042, 'author_profile': 'https://Stackoverflow.com/users/2212042', 'pm_score': 0, 'selected': False, 'text': "<p>While there are some solid answers above, I am surprised by the number of confusions and misunderstandings I have read. This probably proves the idea that one should use java.util.concurrent as much as possible instead of trying to write their own broken concurrent code.</p>\n<p>Back to the question: to summarize, the best practice today is to AVOID notify() in ALL situations due to the lost wakeup problem. Anyone who doesn't understand this should not be allowed to write mission critical concurrency code. If you are worried about the herding problem, one safe way to achieve waking one thread up at a time is to:</p>\n<ol>\n<li>Build an explicit waiting queue for the waiting threads;</li>\n<li>Have each of the thread in the queue wait for its predecessor;</li>\n<li>Have each thread call notifyAll() when done.</li>\n</ol>\n<p>Or you can use Java.util.concurrent.*, which have already implemented this.</p>\n"}, {'answer_id': 44175631, 'author': 'Marco', 'author_id': 3721542, 'author_profile': 'https://Stackoverflow.com/users/3721542', 'pm_score': 3, 'selected': False, 'text': '<p>This answer is a graphical rewriting and simplification of the excellent answer by <a href="https://stackoverflow.com/users/384464/xagyg">xagyg</a>, including comments by <a href="https://stackoverflow.com/users/26039/eran">eran</a>.</p>\n\n<p><strong>Why use notifyAll, even when each product is intended for a single consumer?</strong></p>\n\n<p>Consider producers and consumers, simplified as follows.</p>\n\n<p>Producer:</p>\n\n<pre><code>while (!empty) {\n   wait() // on full\n}\nput()\nnotify()\n</code></pre>\n\n<p>Consumer:</p>\n\n<pre><code>while (empty) {\n   wait() // on empty\n}\ntake()\nnotify()\n</code></pre>\n\n<p>Assume 2 producers and 2 consumers, sharing a buffer of size 1. The following picture depicts a scenario leading to a <strong>deadlock</strong>, which would be avoided if all threads used <strong>notifyAll</strong>.</p>\n\n<p>Each notify is labeled with the thread being woken up.</p>\n\n<p><img src="https://i.stack.imgur.com/IJ5b7.png" alt="deadlock due to notify"></p>\n'}, {'answer_id': 46414690, 'author': 'rajya vardhan', 'author_id': 161243, 'author_profile': 'https://Stackoverflow.com/users/161243', 'pm_score': 2, 'selected': False, 'text': '<p><em>Taken from <a href="http://jtechies.blogspot.in/2012/07/item-69-prefer-concurrency-utilities-to.html" rel="nofollow noreferrer">blog</a> on Effective Java:</em></p>\n\n<pre><code>The notifyAll method should generally be used in preference to notify. \n\nIf notify is used, great care must be taken to ensure liveness.\n</code></pre>\n\n<p>So, what i understand is (from aforementioned blog, comment by "Yann TM" on <a href="https://stackoverflow.com/a/37046/161243">accepted answer</a> and Java <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notify()" rel="nofollow noreferrer">docs</a>):</p>\n\n<ul>\n<li>notify() : JVM awakens one of the waiting threads on this object. Thread selection is made arbitrarily without fairness. So same thread can be awakened again and again. So system\'s state changes but no real progress is made. Thus creating a <a href="https://stackoverflow.com/a/6155978/161243">livelock</a>.</li>\n<li>notifyAll() : JVM awakens all threads and then all threads race for the lock on this object. Now, CPU scheduler selects a thread which acquires lock on this object. This selection process would be much better than selection by JVM. Thus, ensuring liveness.</li>\n</ul>\n'}, {'answer_id': 64409492, 'author': 'haoyu wang', 'author_id': 12824504, 'author_profile': 'https://Stackoverflow.com/users/12824504', 'pm_score': 0, 'selected': False, 'text': "<h2>Waiting queue and blocked queue</h2>\n<p>You can assume there are two kinds of queues associated with each lock object. One is blocked queue containing thread waiting for the monitor lock, other is waiting queue containing thread waiting to be notified. (Thread will be put into waiting queue when they call <code>Object.wait</code>).</p>\n<p>Each time the lock is available, the scheduler choose one thread from blocked queue to execute.</p>\n<p>When <code>notify</code> is called, there will only be one thread in waiting queue are put into blocked queue to contend for the lock, while <code>notifyAll</code> will put all thread in waiting queue into blocked queue.</p>\n<p>Now can you see the difference?<br />\nAlthough in both case there will only be one thread get executed, but with <code>notifyAll</code>, other threads still get a change to be executed(Because they are in the blocked queue) even if they failed to contend the lock.</p>\n<h2>some guidline</h2>\n<p>I basically recommend use <code>notifyAll</code> all the time althrough there may be a little performance penalty.<br />\nAnd use <code>notify</code> only if :</p>\n<ol>\n<li>Any waked thread can make the programe proceed.</li>\n<li>performance is important.</li>\n</ol>\n<p><strong>For example:</strong><br />\n@xagyg 's answer gives a example which <code>notify</code> will cause deadlock. In his example, both producer and consumer are related with the same lock object. So when a producer calls <code>notify</code>, either a producer or a consumer can be notified. But if a producer is woken up it can not make the programe proceed because the buffer is already full.So a deadlock happens.<br />\nThere are two ways to solve it :</p>\n<ol>\n<li>use <code>notifyALl</code> as @xagyg suggests.</li>\n<li>Make procuder and consumer related with different lock object and procuder can only wake up consumer, consumer can only wake up producer. In that case, no matter which consumer is waked, it can consumer the buffer and make the programe proceed.</li>\n</ol>\n"}]
['https://Stackoverflow.com/questions/37026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3894/']