In both of the examples you provided, an intrinsic monitor is used. The second example, however, uses the intrinsic lock of the set
field. Take care when using this practice: if you publish a reference to set
, code outside your class could synchronize on its monitor, which could lead to dead lock.
I think the distinction you're getting at is synchronized
versus using the java.util.concurrent.Lock
API. Most of what you get is added flexibility (from the Lock docs):
The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.
While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.
There are also two method calls which give you more ways to acquire a lock with the Lock API:
lockInterruptibly
: acquire the lock unless the thread is interrupted.
tryLock
: acquire the lock only if it is free at the time of invocation (optional timeout).
The canonical reference for concurrency in Java is 'Java Concurrency in Practice'.