Package java.util.concurrent

Utility classes commonly useful in concurrent programming.

See:
          Description

Interface Summary
BlockingQueue<E> A Queue that additionally supports operations that wait for elements to exist when retrieving them, and wait for space to exist when storing them.
Callable<V> A task that returns a result and may throw an exception.
Cancellable Something, usually a task, that can be cancelled.
ConcurrentMap<K,V> A Map providing additional atomic putIfAbsent and remove methods.
Delayed A mix-in style interface for representing actions, events, etc that should be executed, accessed or acted upon only after a given delay.
Executor An object that executes submitted Runnable tasks.
ExecutorService An Executor that provides methods to manage termination.
Future<V> A Future represents the result of an asynchronous computation.
RejectedExecutionHandler A handler for tasks that cannot be executed by a ThreadPoolExecutor.
ScheduledCancellable A delayed or periodic action that can be cancelled.
ScheduledFuture<V> A delayed result-bearing action that can be cancelled.
ThreadFactory An object that creates new threads on demand.
 

Class Summary
ArrayBlockingQueue<E> A bounded blocking queue backed by an array.
CancellableTask Base class for Cancellable Runnable actions within the Executor framework.
ConcurrentHashMap<K,V> A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.
ConcurrentLinkedQueue<E> An unbounded thread-safe queue based on linked nodes.
CopyOnWriteArrayList<E> A variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.
CopyOnWriteArraySet<E> A Set that uses CopyOnWriteArrayList for all of its operations.
CountDownLatch A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
CyclicBarrier A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.
DelayQueue<E extends Delayed> An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired.
Exchanger<V> An Exchanger provides a synchronization point at which two threads can exchange objects.
Executors Factory and utility methods for Executor, ExecutorService, Future, and Cancellable classes defined in this package.
FairSemaphore A semaphore guaranteeing that threads invoking any of the acquire methods are allocated permits in the order in which their invocation of those methods was processed (first-in-first-out; FIFO).
FutureTask<V> A cancellable asynchronous computation.
LinkedBlockingQueue<E> An optionally-bounded blocking queue based on linked nodes.
PriorityBlockingQueue<E> An unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations.
ScheduledExecutor An Executor that can schedule commands to run after a given delay, or to execute periodically.
Semaphore A counting semaphore.
SynchronousQueue<E> A blocking queue in which each put must wait for a take, and vice versa.
ThreadPoolExecutor An ExecutorService that executes each submitted task using one of possibly several pooled threads.
ThreadPoolExecutor.AbortPolicy A handler for rejected tasks that throws a RejectedExecutionException.
ThreadPoolExecutor.CallerRunsPolicy A handler for rejected tasks that runs the rejected task directly in the calling thread of the execute method, unless the executor has been shut down, in which case the task is discarded.
ThreadPoolExecutor.DiscardOldestPolicy A handler for rejected tasks that discards the oldest unhandled request and then retries execute, unless the executor is shut down, in which case the task is discarded.
ThreadPoolExecutor.DiscardPolicy A handler for rejected tasks that silently discards the rejected task.
TimeUnit A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.
 

Exception Summary
BrokenBarrierException Exception thrown when a thread tries to wait upon a barrier that is in a broken state, or which enters the broken state while the thread is waiting.
CancellationException Exception indicating that the result of a value-producing Cancellable task, such as a FutureTask, cannot be retrieved because the task was cancelled.
ExecutionException Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception.
RejectedExecutionException Exception thrown by an Executor when a task cannot be accepted for execution.
TimeoutException Exception thrown when a blocking operation times out.
 

Package java.util.concurrent Description

Utility classes commonly useful in concurrent programming. This package includes a few small standardized extensible frameworks, as well as some classes that provide useful functionality and are otherwise tedious or difficult to implement. Here are brief descriptions of the main components. See also the locks and atomic packages.

Executors

Executor is a simple standardized interface for defining custom thread-like subsystems, including thread pools, asynchronous IO, and lightweight task frameworks. Depending on which concrete Executor class is being used, tasks may execute in a newly created thread, an existing task-execution thread, or the thread calling execute(), and may execute sequentially or concurrently. Executors also standardize ways of calling threads that compute functions returning results, via a Future. This is supported in part by defining interface Callable, the argument/result analog of Runnable.

ExecutorService provides a more complete framework for executing Runnables. An ExecutorService manages queueing and scheduling of tasks, and allows controlled shutdown. The two primary implementations of ExecutorService are ThreadPoolExecutor, a tunable and flexible thread pool and ScheduledExecutor, which adds support for delayed and periodic task execution. These, and other Executors can be used in conjunction with a CancellableTask or FutureTask to asynchronously start a potentially long-running computation and query to determine if its execution has completed, or cancel it.

The Executors class provides factory methods for the most common kinds and configurations of Executors, as well as a few utility methods for using them.

Queues

The java.util.concurrent ConcurrentLinkedQueue class supplies an efficient scalable thread-safe non-blocking FIFO queue. Five implementations in java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue. The different classes cover the most common usage contexts for producer-consumer, messaging, parallel tasking, and related concurrent designs.

Timing

The TimeUnit class provides multiple granularities (including nanoseconds) for specifying and controlling time-out based operations. Nearly all other classes in the package contain operations based on time-outs in addition to indefinite waits. In all cases that time-outs are used, the time-out specifies the minimum time that the method should wait before indicating that it timed-out. The virtual machine should make a "best effort" to detect time-outs as soon as possible after they occur. Regardless of the efforts of the virtual machine, the normal scheduling mechanisms, and the need to re-acquire locks in many cases, can lead to an indefinite amount of time elapsing between a time-out being detected and a thread actually executing again after that time-out.

Synchronizers

Five classes aid common special-purpose synchronization idioms. Semaphore and FairSemaphore are classic concurrency tools. CountDownLatch is very simple yet very common utility for blocking until a single signal, event, or condition holds. A CyclicBarrier is a resettable multiway synchronization point common in some styles of parallel programming. An Exchanger allows two threads to exchange objects at a rendezvous point.

Concurrent Collections

Besides Queues, this package supplies a few Collection implementations designed for use in multithreaded contexts: ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteArraySet.

The "Concurrent" prefix used with some classes in this package is a shorthand indicating several differences from similar "synchronized" classes. For example java.util.Hashtable and Collections.synchronizedMap(new HashMap()) are synchronized. But ConcurrentHashMap is "concurrent". A concurrent collection is thread-safe, but not governed by a single exclusion lock. In the particular case of ConcurrentHashMap, it safely permits any number of concurrent reads as well as a tunable number of concurrent writes. There may still be a role for "synchronized" classes in some multithreaded programs -- they can sometimes be useful when you need to prevent all access to a collection via a single lock, at the expense of much poor scalability. In all other cases, "concurrent" versions are normally preferable.

Most concurrent Collection implementations (including most Queues) also differ from the usual java.util conventions in that their Iterators provide weakly consistent rather than fast-fail traversal. A weakly consistent iterator is thread-safe, but does not necessarily freeze the collection while iterating, so it may (or may not) reflect any updates since the iterator was created.