How do explicit locks compare with the use of the synchronized
keyword? Here are the parallels: Synchronized Instance Methods
A synchronized instance method such as:
public synchronized void transfer()
{
// perform transfer
}
is equivalent to:
public void transfer()
{
this.intrinsicLock.lock();
try
{
// perform transfer
}
finally
{
this.intrinsicLock.unlock();
}
}
where the intrinsicLock is the lock
intrinsically associated with the object instance for that method.
Synchronized Class Methods
A synchronized class (static) method is similar to the above, except that
the intrinsic lock is the one associated with the class's associated class
object.
The wait() Method
A call to the wait() method is equivalent to: intrinsicCondition.await();
The notifyAll() Method
A call to the notifyAll() method is
equivalent to: intrinsicCondition.signalAll();
Pros and Cons
Using the synchronized mechanism tends to be much more concise. Using
explicit locks and conditions is much more flexible. For example, using synchronized
is subject to the following restrictions:
- You cannot interrupt a thread that is trying to acquire a lock
- You cannot specify a timeout when trying to acquire a lock
- Having a single condition per lock can be less than ideal.
|