What does synchronized/wait/notifyAll do in Java?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In Java, concurrency is a crucial aspect for developers to understand, especially when dealing with multi-threaded applications. Three commonly used keywords in the Java concurrency paradigm are synchronized
, wait()
, and notifyAll()
. These are essential tools provided by the Java language to manage inter-thread communication and synchronization effectively. Below, we delve into the details of each and illustrate their significance with examples.
Synchronized
The synchronized
keyword in Java is used to control access to a particular block of code or method. When a method or block is declared as synchronized
, it ensures that only one thread can execute the block at any given time. This is especially useful in preventing race conditions and ensuring data consistency when multiple threads are accessing shared resources.
Technical Explanation
- Method Synchronization: When a method is synchronized, the thread must acquire the method's lock (or the monitor) before executing it.
- Block Synchronization: You can also synchronize a block of code within a method, by specifying the object whose lock will be acquired.
Example
- When a thread calls
wait()on an object, it releases the lock on that object and enters a waiting state. - It must reclaim the object’s monitor (i.e., be notified) to proceed with execution.
- The
notify()method wakes up a single thread that is waiting on the object's monitor. - The choice of which thread to wake up is arbitrary, and it's advised to use this method when only one thread needs to proceed.
notifyAll()wakes up all threads that are waiting on the object's monitor.- All waiting threads compete for the monitor, but only one will proceed.
- **Use
notifyAll()overnotify()**: It's often safer to callnotifyAll()instead ofnotify()unless you are very sure about which thread will be woken up. - Synchronized Collections: Java provides built-in synchronized collections like
VectorandHashtable. However, newer constructs such asConcurrentHashMapandCopyOnWriteArrayListoffer better performance. - Explicit Locks: Consider using Java's
java.util.concurrent.locksfor more advanced locking mechanisms that offer try-locking capabilities and more flexible wait strategies. - Deadlocks: Improper use of synchronized blocks can lead to deadlocks where two or more threads are waiting indefinitely for each other to release locks.
- Lost Wake-Up Problem: If
notify()is issued but there are no threads waiting, the notification is lost. It’s essential to implement waiting loops using conditions.

