}
If you use an unsynchronized collection concurrently the result is undefinedif you are lucky the error will be
detected by the collection and you will get a ConcurrentModificationException. If you are
unlucky the collection will quietly become corrupt.
21.11.2. The Concurrent Collections
The java.util.concurrent subpackage provides collection implementations that are not only safe for
concurrent use but are specially designed to support such use.
When using a collection concurrently, you can't be sure when a collection might be empty, or, for a capacity
constrained collection, when it might be full. In such circumstances it is useful to be able to wait until an
element appears or until space for an element appears. The BlockingQueue
Queue
public voidput(E elem)throws InterruptedException
Adds the specified element to this queue, waiting if necessary for space to
become available.
public booleanoffer(E elem, long time, TimeUnit unit)tHRows
InterruptedException
Adds the specified element to this queue, waiting if necessary up to the
specified waiting time for space to become available. Returns TRue if the
element was added, and false if the specified waiting time elapsed before
space became available.
public Etake()throws InterruptedException
Returns and removes the head of this queue, waiting if necessary for the
queue to be non-empty.
public Epoll(long time, TimeUnit unit)throws
InterruptedException
Returns and removes the head of this queue, waiting if necessary up to the
specified waiting time for the queue to be non-empty. Returns the head of the
queue, or null if the specified waiting time elapsed before an element
became available.
As these are all potentially blocking operations. They support cancellation by throwing an
InterruptedException in response to the current thread being interrupted.
You specify the waiting times with a long to indicate the time, and a value of the enum
java.util.concurrent.TimeUnit to indicate the units. The enum TimeUnit has the constants
NANOSECONDS, MICROSECONDS, MILLISECONDS, and SECONDS.
A BlockingQueue may be capacity constrained. The remainingCapacity method returns the number
of elements that can be put in the queue without causing blockingbut note that if multiple threads are using the
queue it doesn't guarantee how many elements an individual thread may be able to add without blocking. If