img
The Concurrent Collections
As explained, the concurrent API defines several collection classes that have been engineered
for concurrent operation. They are
ArrayBlockingQueue
ConcurrentHashMap
ConcurrentLinkedQueue
ConcurrentSkipListMap (Added by Java SE 6.)
ConcurrentSkipListSet (Added by Java SE 6.)
CopyOnWriteArraylist
CopyOnWriteArraySet
DelayQueue
LinkedBlockingDeque (Added by Java SE 6.)
LinkedBlockingQueue
PriorityBlockingQueue
SynchronousQueue
These offer concurrent alternatives to their related classes defined by the Collections
Framework. These collections work much like the other collections except that they provide
concurrency support. Programmers familiar with the Collections Framework will have no
trouble using these concurrent collections.
Locks
The java.util.concurrent.locks package provides support for locks, which are objects that
offer an alternative to using synchronized to control access to a shared resource. In general,
here is how a lock works. Before accessing a shared resource, the lock that protects that
resource is acquired. When access to the resource is complete, the lock is released. If a second
thread attempts to acquire the lock when it is in use by another thread, the second thread
will suspend until the lock is released. In this way, conflicting access to a shared resource
is prevented.
Locks are particularly useful when multiple threads need to access the value of shared
data. For example, an inventory application might have a thread that first confirms that an
item is in stock and then decreases the number of items on hand as each sale occurs. If two
or more of these threads are running, then without some form of synchronization, it would
be possible for one thread to be in middle of a transaction when the second thread begins
its transaction. The result could be that both threads would assume that adequate inventory
exists, even if there is only sufficient inventory on hand to satisfy one sale. In this type of
situation, a lock offers a convenient means of handling the needed synchronization.
All locks implement the Lock interface. The methods defined by Lock are shown in
Table 26-1. In general, to acquire a lock, call lock( ). If the lock is unavailable, lock( ) will
wait. To release a lock, call unlock( ). To see if a lock is available, and to acquire it if it is, call
tryLock( ). This method will not wait for the lock if it is unavailable. Instead, it returns true
if the lock is acquired and false otherwise. The newCondition( ) method returns a Condition
object associated with the lock. Using a Condition, you gain detailed control of the lock
through methods such as await( ) and signal( ), which provide functionality similar to
Object.wait( ) and Object.notify( ).
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home