What is the difference between notify() and notifyAll(), and which should you use?
notify() wakes up exactly one arbitrary thread from the object's wait-set, while notifyAll() wakes every thread currently waiting on that object, and each one re-checks its own condition after waking to decide whether to proceed or go back to waiting. As a default, you should use notifyAll(): notify() is only safe in the narrow case where every waiting thread is waiting on the exact same condition and any one of them is equally able to proceed once woken. When there are different kinds of waiters on the same lock, for example producers and consumers both waiting on the same object, notify() might wake a producer when what's actually needed is a consumer, and repeating this pattern can leave threads waiting forever -- a lost wakeup. notifyAll() avoids this problem entirely because every thread gets a chance to re-evaluate its own condition, so it is always safe even though it can occasionally wake more threads than strictly necessary.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response