Java Reference
In-Depth Information
Simplifying Synchronization with Locks
Problem
You want an easier means of synchronizing threads.
Solution
Use the
Lock
mechanism in
java.util.concurrent.locks
.
Discussion
Use the
java.util.concurrent.locks
package; its major interface is
Lock
. This interface
has several methods for locking and one for unlocking. The general pattern for using it is:
Lock thelock
= ....
try
try
{
lock
.
lock
( );
// do the work that is protected by the lock
}
finally
finally
{
lock
.
unlock
( );
}
The point of putting the
unlock()
call in the
finally
block is, of course, to ensure that it is
not bypassed if an exception occurs (the code may also include one or more
catch
blocks, as
required by the work being performed).
The improvement here, compared with the traditional synchronized methods and blocks, is
that using a
Lock
actually looks like a locking operation! And, as I mentioned, several means
of locking are available, shown in
Table 22-1
.