Chapter 26: The Concurrency Utilities 809
java.util.concurrent.lockssupplies an implementation ofLockcalledReentrantLock.
ReentrantLockimplements areentrant lock,which is a lock that can be repeatedly entered
by the thread that currently holds the lock. (Of course, in the case of a thread reentering a
lock, all calls tolock( )must be offset by an equal number of calls tounlock( ).) Otherwise,
a thread seeking to acquire the lock will suspend until the lock is not in use.
The following program demonstrates the use of a lock. It creates two threads that access
a shared resource calledShared.count. Before a thread can accessShared.count, it must obtain
a lock. After obtaining the lock,Shared.countis incremented and then, before releasing the
lock, the thread sleeps. This causes the second thread to attempt to obtain the lock.
However, because the lock is still held by the first thread, the second thread must wait until
the first thread stops sleeping and releases the lock. The output shows that access to
Shared.countis, indeed, synchronized by the lock.
// A simple lock example.
import java.util.concurrent.locks.*;
class LockDemo {
public static void main(String args[]) {
ReentrantLock lock = new ReentrantLock();
new LockThread(lock, "A");
new LockThread(lock, "B");
}
}
Method Description
void lock( ) Waits until the invoking lock can be acquired.
void lockInterruptibly( )
throws InterruptedException
Waits until the invoking lock can be acquired, unless
interrupted.
Condition newCondition( ) Returns aConditionobject that is associated with the
invoking lock.
boolean tr yLock( ) Attempts to acquire the lock. This method will not wait
if the lock is unavailable. Instead, it returnstrueif the
lock has been acquired andfalseif the lock is currently
in use by another thread.
boolean tr yLock(longwait, TimeUnittu)
throws InterruptedException
Attempts to acquire the lock. If the lock is unavailable,
this method will wait no longer than the period specified
bywait,which is intuunits. It returnstrueif the lock has
been acquired andfalseif the lock cannot be acquired
within the specified period.
void unlock( ) Releases the lock.
TABLE 26-1 TheLockMethods