About
Another way to create synchronized code is with synchronized statements.
Articles Related
Syntax
Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock.
public void addName(String name) {
// this refer to the instance
// the addName method needs to synchronize changes to lastName and nameCount
synchronized(this) {
lastName = name;
nameCount++;
}
// but also needs to avoid synchronizing other objects' methods
nameList.add(name);
}
Process
The synchronized statement:
- computes a reference to an object;
- attempts to perform a lock action on that object's monitor and does not proceed further until the lock action has successfully completed.
- execute its body after the lock action has been performed
- unlock the same monitor if the execution of the body is ever completed, either normally or abruptly.
Usage
- Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking a unique statement (in our case nameList.add)
- Invoking other objects' methods from synchronized code can create problems. See Liveness.
- Synchronized statements are also useful for improving concurrency with fine-grained synchronization.