A synchronized statement acquires a mutual-exclusion lock (§17.1) on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock.
SynchronizedStatement:
synchronized ( Expression ) Block
The type of Expression must be a reference type, or a compile-time error occurs.
A synchronized statement is executed by first evaluating the Expression. Then:
-
If evaluation of the Expression completes abruptly for some reason, then the
synchronizedstatement completes abruptly for the same reason. -
Otherwise, if the value of the Expression is
null, aNullPointerExceptionis thrown. -
Otherwise, let the non-
nullvalue of the Expression beV. The executing thread locks the monitor associated withV. Then the Block is executed, and then there is a choice:- If execution of the Block completes normally, then the monitor is unlocked and the
synchronizedstatement completes normally. - If execution of the Block completes abruptly for any reason, then the monitor is unlocked and the
synchronizedstatement completes abruptly for the same reason.
- If execution of the Block completes normally, then the monitor is unlocked and the
The locks acquired by synchronized statements are the same as the locks that are acquired implicitly by synchronized methods (§8.4.3.6). A single thread may acquire a lock more than once.
Acquiring the lock associated with an object does not in itself prevent other threads from accessing fields of the object or invoking un-synchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.
Example 14.19-1. The synchronized Statement
class Test {
public static void main(String[] args) {
Test t = new Test();
synchronized(t) {
synchronized(t) {
System.out.println("made it!");
}
}
}
}
This program produces the output:
made it!
Note that this program would deadlock if a single thread were not permitted to lock a monitor more than once.