Java Reference ยท Keywords and Statements
The synchronized keyword
Reference for Java synchronized: synchronized methods and blocks, intrinsic locks, reentrancy, visibility guarantees, deadlock risks and alternatives.
synchronized gives a thread exclusive access to a piece of code by acquiring the intrinsic lock (monitor) of an object. Only one thread at a time can hold the lock of a given object; others that try to enter a block guarded by the same lock wait until it is released.
It also guarantees visibility: everything a thread wrote before releasing a lock is visible to the thread that acquires the same lock afterwards. You can synchronize a whole method or just a block of code.
synchronized void increment() { count++; } void add(int n) { synchronized (lock) { count += n; } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
synchronized returnType method(...) { ... } // locks this static synchronized returnType method(...) { ... } // locks the Class object synchronized (expression) { ... } // locks the given object
| Form | Lock held |
|---|---|
| Instance method | this |
| Static method | the Class object, such as Account.class |
| Block | the object the expression evaluates to (must not be null, which throws NullPointerException) |
Usage notes
- Reentrant: a thread that already holds a lock can enter other blocks guarded by the same lock without blocking itself.
- Always the same lock. Two threads only exclude each other if they synchronize on the same object. Locking on different instances protects nothing.
- Prefer private lock objects (
private final Object lock = new Object()) overthis, so outside code cannot interfere by locking your object. Never lock on strings, boxed numbers or other shared, interned objects. - Keep critical sections short and avoid calling unknown code (callbacks, I/O) while holding a lock.
- Deadlock: two threads that take two locks in opposite orders can wait forever. Acquire locks in one global order.
wait(),notify()andnotifyAll()must be called while holding the object's lock, otherwiseIllegalMonitorStateExceptionis thrown.- Exceptions release the lock automatically when they leave the block.
- Constructors cannot be
synchronized; the keyword is not part of the method signature and is not inherited by overriding methods. - Virtual threads (Java 21+): blocking inside
synchronizedpinned the carrier thread up to Java 23; Java 24 removed that limitation for most cases. - Alternatives:
ReentrantLock(try-lock, timeouts, fairness),AtomicIntegerand friends for single variables, and concurrent collections.
Related
volatile,final,static- Lessons: Synchronization, Locks, Deadlocks, wait and notify