Java Reference
In-Depth Information
Table 22-1. Locking methods of the Lock class
Return
type
Method
Meaning
void
Get the lock, even if you have to wait until anoth-
er thread frees it first.
lock( )
boolean
Get the lock only if it is free right now.
tryLock( )
boolean
Try to get the lock, but only wait for the length of
time indicated.
tryLock(long time, TimeUnit units) throws
InterruptedException
void
Get the lock, waiting unless interrupted.
lockInterruptibly( ) throws InterruptedEx-
ception
void
Release the lock.
unlock( )
The TimeUnit class lets you specify the units for the amount of time specified, including
TimeUnit.SECONDS , TimeUnit.MILLISECONDS , TimeUnit.MICROSECONDS , and TimeUn-
it.NANOSECONDS .
In all cases, the lock must be released with unlock() before it can be locked again.
The standard Lock is useful in many applications, but depending on the application's require-
ments, other types of locks may be more appropriate. Applications with asymmetric load pat-
terns may benefit from a common pattern called the “reader-writer lock”; I call this one a
Readers-Writer lock to emphasize that there can be many readers but only one writer. It's ac-
tually a pair of interconnected locks; any number of readers can hold the read lock and read
the data, as long as it's not being written (shared read access). A thread trying to lock the
write lock, however, waits until all the readers are finished, then locks them out until the
writer is finished (exclusive write access). To support this pattern, both the ReadWriteLock
interface and the implementing class ReentrantReadWriteLock are available. The interface
has only two methods, readLock( ) and writeLock( ) , which provide a reference to the
appropriate Lock implementation. These methods do not, in themselves, lock or unlock the
locks ; they only provide access to them, so it is common to see code like:
rwlock.readLock( ).lock( );
...
rwlock.readLock( ).unlock( );
Search WWH ::




Custom Search