jsr166y-BlenderRev

BlenderRev generated at Thu Sep 10 14:25:42 2009
build/solaris-sparc/docs/api generated at Wed Sep 9 11:48:26 2009
../master/build/solaris-sparc/docs/api generated at Wed Sep 9 12:54:12 2009

java.util (1 class)

Random

java.util.concurrent (7 interfaces, 12 classes, 159 methods, 1 field)

AbstractExecutorService BlockingQueue ConcurrentLinkedQueue CountDownLatch Executor ExecutorService ForkJoinPool ForkJoinPool.ForkJoinWorkerThreadFactory ForkJoinPool.ManagedBlocker ForkJoinTask ForkJoinWorkerThread Future LinkedTransferQueue Phaser RecursiveAction RecursiveTask ScheduledThreadPoolExecutor ThreadLocalRandom TransferQueue package-summary

java.util.Random

Random.CLASS_COMMENT

java.util
Class Random


 java.lang.Object
  extended by java.util.Random
 
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
ThreadLocalRandom

public class Random
 extends Object
 implements Serializable

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2 , Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random . Java implementations must use all the algorithms shown here for the class Random , for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method Math.random() simpler to use.

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

Since:
1.0
See Also:
Serialized Form

java.util
Class Random

java.lang.Object
  extended by java.util.Random
All Implemented Interfaces:
Serializable

public class Random
extends Object
implements Serializable

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method Math.random() simpler to use.

Since:
1.0
See Also:
Serialized Form

java.util
Class Random

java.lang.Object
  extended by java.util.Random
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
ThreadLocalRandom

public class Random
extends Object
implements Serializable

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method Math.random() simpler to use.

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

Since:
1.0
See Also:
Serialized Form

java.util.concurrent.AbstractExecutorService

AbstractExecutorService.CLASS_COMMENT

java.util.concurrent
Class AbstractExecutorService


 java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
 
All Implemented Interfaces:
Executor , ExecutorService
Direct Known Subclasses:
ForkJoinPool ThreadPoolExecutor , ThreadPoolExecutor

public abstract class AbstractExecutorService
 extends Object
 implements ExecutorService

Provides default implementations of ExecutorService execution methods. This class implements the submit , invokeAny and invokeAll methods using a RunnableFuture returned by newTaskFor , which defaults to the FutureTask class provided in this package. For example, the implementation of submit(Runnable) creates an associated RunnableFuture that is executed and returned. Subclasses may override the newTaskFor methods to return RunnableFuture implementations other than FutureTask .

Extension example . Here is a sketch of a class that customizes ThreadPoolExecutor to use a CustomTask class instead of the default FutureTask :


 public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
 
   static class CustomTask<V> implements RunnableFuture<V> {...}
 
   protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
       return new CustomTask<V>(c);
   }
   protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
       return new CustomTask<V>(r, v);
   }
   // ... add constructors, etc.
 }
 

Since:
1.5

java.util.concurrent
Class AbstractExecutorService

java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
All Implemented Interfaces:
Executor, ExecutorService
Direct Known Subclasses:
ThreadPoolExecutor

public abstract class AbstractExecutorService
extends Object
implements ExecutorService

Provides default implementations of ExecutorService execution methods. This class implements the submit, invokeAny and invokeAll methods using a RunnableFuture returned by newTaskFor, which defaults to the FutureTask class provided in this package. For example, the implementation of submit(Runnable) creates an associated RunnableFuture that is executed and returned. Subclasses may override the newTaskFor methods to return RunnableFuture implementations other than FutureTask.

Extension example. Here is a sketch of a class that customizes ThreadPoolExecutor to use a CustomTask class instead of the default FutureTask:

 public class CustomThreadPoolExecutor extends ThreadPoolExecutor {

   static class CustomTask<V> implements RunnableFuture<V> {...}

   protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
       return new CustomTask<V>(c);
   }
   protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
       return new CustomTask<V>(r, v);
   }
   // ... add constructors, etc.
 }
 

Since:
1.5

java.util.concurrent
Class AbstractExecutorService

java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
All Implemented Interfaces:
Executor, ExecutorService
Direct Known Subclasses:
ForkJoinPool, ThreadPoolExecutor

public abstract class AbstractExecutorService
extends Object
implements ExecutorService

Provides default implementations of ExecutorService execution methods. This class implements the submit, invokeAny and invokeAll methods using a RunnableFuture returned by newTaskFor, which defaults to the FutureTask class provided in this package. For example, the implementation of submit(Runnable) creates an associated RunnableFuture that is executed and returned. Subclasses may override the newTaskFor methods to return RunnableFuture implementations other than FutureTask.

Extension example. Here is a sketch of a class that customizes ThreadPoolExecutor to use a CustomTask class instead of the default FutureTask:

 public class CustomThreadPoolExecutor extends ThreadPoolExecutor {

   static class CustomTask<V> implements RunnableFuture<V> {...}

   protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
       return new CustomTask<V>(c);
   }
   protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
       return new CustomTask<V>(r, v);
   }
   // ... add constructors, etc.
 }
 

Since:
1.5

java.util.concurrent.BlockingQueue

BlockingQueue.CLASS_COMMENT

java.util.concurrent
Interface BlockingQueue<E>

Type Parameters:
E - the type of elements held in this collection
All Superinterfaces:
Collection<E>, Iterable<E>, Queue<E>
All Known Subinterfaces:
BlockingDeque <E>, TransferQueue<E>
All Known Implementing Classes:
ArrayBlockingQueue , DelayQueue , LinkedBlockingDeque , LinkedBlockingQueue , LinkedTransferQueue , PriorityBlockingQueue , SynchronousQueue

public interface BlockingQueue<E>
 extends Queue<E>

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false , depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. These methods are summarized in the following table:

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable

A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add , put or offer a null . A null is used as a sentinel value to indicate failure of poll operations.

A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE .

BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the Collection interface. So, for example, it is possible to remove an arbitrary element from a queue using remove(x) . However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll , containsAll , retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c .

A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers.

Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.


 class Producer implements Runnable {
   private final BlockingQueue queue;
   Producer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { queue.put(produce()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   Object produce() { ... }
 }
 
 class Consumer implements Runnable {
   private final BlockingQueue queue;
   Consumer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { consume(queue.take()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   void consume(Object x) { ... }
 }
 
 class Setup {
   void main() {
     BlockingQueue q = new SomeQueueImplementation();
     Producer p = new Producer(q);
     Consumer c1 = new Consumer(q);
     Consumer c2 = new Consumer(q);
     new Thread(p).start();
     new Thread(c1).start();
     new Thread(c2).start();
   }
 }
 

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.

This interface is a member of the Java Collections Framework.

Since:
1.5

java.util.concurrent
Interface BlockingQueue<E>

Type Parameters:
E - the type of elements held in this collection
All Superinterfaces:
Collection<E>, Iterable<E>, Queue<E>
All Known Subinterfaces:
BlockingDeque<E>
All Known Implementing Classes:
ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue

public interface BlockingQueue<E>
extends Queue<E>

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. These methods are summarized in the following table:

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable

A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations.

A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE.

BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the Collection interface. So, for example, it is possible to remove an arbitrary element from a queue using remove(x). However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers.

Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.

 class Producer implements Runnable {
   private final BlockingQueue queue;
   Producer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { queue.put(produce()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   Object produce() { ... }
 }

 class Consumer implements Runnable {
   private final BlockingQueue queue;
   Consumer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { consume(queue.take()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   void consume(Object x) { ... }
 }

 class Setup {
   void main() {
     BlockingQueue q = new SomeQueueImplementation();
     Producer p = new Producer(q);
     Consumer c1 = new Consumer(q);
     Consumer c2 = new Consumer(q);
     new Thread(p).start();
     new Thread(c1).start();
     new Thread(c2).start();
   }
 }
 

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.

This interface is a member of the Java Collections Framework.

Since:
1.5

java.util.concurrent
Interface BlockingQueue<E>

Type Parameters:
E - the type of elements held in this collection
All Superinterfaces:
Collection<E>, Iterable<E>, Queue<E>
All Known Subinterfaces:
BlockingDeque<E>, TransferQueue<E>
All Known Implementing Classes:
ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, SynchronousQueue

public interface BlockingQueue<E>
extends Queue<E>

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. These methods are summarized in the following table:

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable

A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations.

A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE.

BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the Collection interface. So, for example, it is possible to remove an arbitrary element from a queue using remove(x). However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers.

Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.

 class Producer implements Runnable {
   private final BlockingQueue queue;
   Producer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { queue.put(produce()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   Object produce() { ... }
 }

 class Consumer implements Runnable {
   private final BlockingQueue queue;
   Consumer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while (true) { consume(queue.take()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   void consume(Object x) { ... }
 }

 class Setup {
   void main() {
     BlockingQueue q = new SomeQueueImplementation();
     Producer p = new Producer(q);
     Consumer c1 = new Consumer(q);
     Consumer c2 = new Consumer(q);
     new Thread(p).start();
     new Thread(c1).start();
     new Thread(c2).start();
   }
 }
 

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.

This interface is a member of the Java Collections Framework.

Since:
1.5

java.util.concurrent.ConcurrentLinkedQueue (1 method)

ConcurrentLinkedQueue.add(java.lang.Object)

add


 public boolean add(E e)
Inserts the specified element at the tail of this queue.

Specified by:
add in interface Collection<E>
Specified by:
add in interface Queue<E>
Overrides:
add in class AbstractQueue<E>
Parameters:
e - the element to add
Returns:
true (as specified by Collection.add(E) )
Throws:
NullPointerException - if the specified element is null

add

public boolean add(E e)
Inserts the specified element at the tail of this queue.

Specified by:
add in interface Collection<E>
Specified by:
add in interface Queue<E>
Overrides:
add in class AbstractQueue<E>
Returns:
true (as specified by Collection.add(E))
Throws:
NullPointerException - if the specified element is null

add

public boolean add(E e)
Inserts the specified element at the tail of this queue.

Specified by:
add in interface Collection<E>
Specified by:
add in interface Queue<E>
Overrides:
add in class AbstractQueue<E>
Parameters:
e - the element to add
Returns:
true (as specified by Collection.add(E))
Throws:
NullPointerException - if the specified element is null

java.util.concurrent.CountDownLatch

CountDownLatch.CLASS_COMMENT

java.util.concurrent
Class CountDownLatch


 java.lang.Object
  extended by java.util.concurrent.CountDownLatch
 

public class CountDownLatch
 extends Object

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count . The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier .

A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown() . A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

Sample usage: Here is a pair of classes in which a group of worker threads use two countdown latches:

  • The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed;
  • The second is a completion signal that allows the driver to wait until all workers have completed.

 class Driver { // ...
   void main() throws InterruptedException {
     CountDownLatch startSignal = new CountDownLatch(1);
     CountDownLatch doneSignal = new CountDownLatch(N);
 
     for (int i = 0; i < N; ++i) // create and start threads
       new Thread(new Worker(startSignal, doneSignal)).start();
 
     doSomethingElse();            // don't let run yet
     startSignal.countDown();      // let all threads proceed
     doSomethingElse();
     doneSignal.await();           // wait for all to finish
   }
 }
 
 class Worker implements Runnable {
   private final CountDownLatch startSignal;
   private final CountDownLatch doneSignal;
   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
      this.startSignal = startSignal;
      this.doneSignal = doneSignal;
   }
   public void run() {
      try {
        startSignal.await();
        doWork();
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
   }
 
   void doWork() { ... }
 }
 
 

Another typical usage would be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a CyclicBarrier .)


 class Driver2 { // ...
   void main() throws InterruptedException {
     CountDownLatch doneSignal = new CountDownLatch(N);
     Executor e = ...
 
     for (int i = 0; i < N; ++i) // create and start threads
       e.execute(new WorkerRunnable(doneSignal, i));
 
     doneSignal.await();           // wait for all to finish
   }
 }
 
 class WorkerRunnable implements Runnable {
   private final CountDownLatch doneSignal;
   private final int i;
   WorkerRunnable(CountDownLatch doneSignal, int i) {
      this.doneSignal = doneSignal;
      this.i = i;
   }
   public void run() {
      try {
        doWork(i);
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
   }
 
   void doWork() { ... }
 }
 
 

Memory consistency effects: Until the count reaches zero, actions Actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread.

Since:
1.5

java.util.concurrent
Class CountDownLatch

java.lang.Object
  extended by java.util.concurrent.CountDownLatch

public class CountDownLatch
extends Object

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown(). A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

Sample usage: Here is a pair of classes in which a group of worker threads use two countdown latches:

  • The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed;
  • The second is a completion signal that allows the driver to wait until all workers have completed.
 class Driver { // ...
   void main() throws InterruptedException {
     CountDownLatch startSignal = new CountDownLatch(1);
     CountDownLatch doneSignal = new CountDownLatch(N);

     for (int i = 0; i < N; ++i) // create and start threads
       new Thread(new Worker(startSignal, doneSignal)).start();

     doSomethingElse();            // don't let run yet
     startSignal.countDown();      // let all threads proceed
     doSomethingElse();
     doneSignal.await();           // wait for all to finish
   }
 }

 class Worker implements Runnable {
   private final CountDownLatch startSignal;
   private final CountDownLatch doneSignal;
   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
      this.startSignal = startSignal;
      this.doneSignal = doneSignal;
   }
   public void run() {
      try {
        startSignal.await();
        doWork();
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
   }

   void doWork() { ... }
 }

 

Another typical usage would be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a CyclicBarrier.)

 class Driver2 { // ...
   void main() throws InterruptedException {
     CountDownLatch doneSignal = new CountDownLatch(N);
     Executor e = ...

     for (int i = 0; i < N; ++i) // create and start threads
       e.execute(new WorkerRunnable(doneSignal, i));

     doneSignal.await();           // wait for all to finish
   }
 }

 class WorkerRunnable implements Runnable {
   private final CountDownLatch doneSignal;
   private final int i;
   WorkerRunnable(CountDownLatch doneSignal, int i) {
      this.doneSignal = doneSignal;
      this.i = i;
   }
   public void run() {
      try {
        doWork(i);
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
   }

   void doWork() { ... }
 }

 

Memory consistency effects: Actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread.

Since:
1.5

java.util.concurrent
Class CountDownLatch

java.lang.Object
  extended by java.util.concurrent.CountDownLatch

public class CountDownLatch
extends Object

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown(). A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

Sample usage: Here is a pair of classes in which a group of worker threads use two countdown latches:

  • The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed;
  • The second is a completion signal that allows the driver to wait until all workers have completed.
 class Driver { // ...
   void main() throws InterruptedException {
     CountDownLatch startSignal = new CountDownLatch(1);
     CountDownLatch doneSignal = new CountDownLatch(N);

     for (int i = 0; i < N; ++i) // create and start threads
       new Thread(new Worker(startSignal, doneSignal)).start();

     doSomethingElse();            // don't let run yet
     startSignal.countDown();      // let all threads proceed
     doSomethingElse();
     doneSignal.await();           // wait for all to finish
   }
 }

 class Worker implements Runnable {
   private final CountDownLatch startSignal;
   private final CountDownLatch doneSignal;
   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
      this.startSignal = startSignal;
      this.doneSignal = doneSignal;
   }
   public void run() {
      try {
        startSignal.await();
        doWork();
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
   }

   void doWork() { ... }
 }

 

Another typical usage would be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a CyclicBarrier.)

 class Driver2 { // ...
   void main() throws InterruptedException {
     CountDownLatch doneSignal = new CountDownLatch(N);
     Executor e = ...

     for (int i = 0; i < N; ++i) // create and start threads
       e.execute(new WorkerRunnable(doneSignal, i));

     doneSignal.await();           // wait for all to finish
   }
 }

 class WorkerRunnable implements Runnable {
   private final CountDownLatch doneSignal;
   private final int i;
   WorkerRunnable(CountDownLatch doneSignal, int i) {
      this.doneSignal = doneSignal;
      this.i = i;
   }
   public void run() {
      try {
        doWork(i);
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
   }

   void doWork() { ... }
 }

 

Memory consistency effects: Until the count reaches zero, actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread.

Since:
1.5

java.util.concurrent.Executor

Executor.CLASS_COMMENT

java.util.concurrent
Interface Executor

All Known Subinterfaces:
ExecutorService , ScheduledExecutorService
All Known Implementing Classes:
AbstractExecutorService , ForkJoinPool , ScheduledThreadPoolExecutor , ThreadPoolExecutor

public interface Executor

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:


 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());
 ...
 
However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread:

 class DirectExecutor implements Executor {
     public void execute(Runnable r) {
         r.run();
     }
 }
More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task.

 class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
         new Thread(r).start();
     }
 }
Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.

 class SerialExecutor implements Executor {
     final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
     final Executor executor;
     Runnable active;
 
     SerialExecutor(Executor executor) {
         this.executor = executor;
     }
 
     public synchronized void execute(final Runnable r) {
         tasks.offer(new Runnable() {
             public void run() {
                 try {
                     r.run();
                 } finally {
                     scheduleNext();
                 }
             }
         });
         if (active == null) {
             scheduleNext();
         }
     }
 
     protected synchronized void scheduleNext() {
         if ((active = tasks.poll()) != null) {
             executor.execute(active);
         }
     }
 }
The Executor implementations provided in this package implement ExecutorService , which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

Since:
1.5

java.util.concurrent
Interface Executor

All Known Subinterfaces:
ExecutorService, ScheduledExecutorService
All Known Implementing Classes:
AbstractExecutorService, ScheduledThreadPoolExecutor, ThreadPoolExecutor

public interface Executor

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:

 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());
 ...
 
However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread:
 class DirectExecutor implements Executor {
     public void execute(Runnable r) {
         r.run();
     }
 }
More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task.
 class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
         new Thread(r).start();
     }
 }
Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.
 class SerialExecutor implements Executor {
     final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
     final Executor executor;
     Runnable active;

     SerialExecutor(Executor executor) {
         this.executor = executor;
     }

     public synchronized void execute(final Runnable r) {
         tasks.offer(new Runnable() {
             public void run() {
                 try {
                     r.run();
                 } finally {
                     scheduleNext();
                 }
             }
         });
         if (active == null) {
             scheduleNext();
         }
     }

     protected synchronized void scheduleNext() {
         if ((active = tasks.poll()) != null) {
             executor.execute(active);
         }
     }
 }
The Executor implementations provided in this package implement ExecutorService, which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

Since:
1.5

java.util.concurrent
Interface Executor

All Known Subinterfaces:
ExecutorService, ScheduledExecutorService
All Known Implementing Classes:
AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor

public interface Executor

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:

 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());
 ...
 
However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread:
 class DirectExecutor implements Executor {
     public void execute(Runnable r) {
         r.run();
     }
 }
More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task.
 class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
         new Thread(r).start();
     }
 }
Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.
 class SerialExecutor implements Executor {
     final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
     final Executor executor;
     Runnable active;

     SerialExecutor(Executor executor) {
         this.executor = executor;
     }

     public synchronized void execute(final Runnable r) {
         tasks.offer(new Runnable() {
             public void run() {
                 try {
                     r.run();
                 } finally {
                     scheduleNext();
                 }
             }
         });
         if (active == null) {
             scheduleNext();
         }
     }

     protected synchronized void scheduleNext() {
         if ((active = tasks.poll()) != null) {
             executor.execute(active);
         }
     }
 }
The Executor implementations provided in this package implement ExecutorService, which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

Since:
1.5

java.util.concurrent.ExecutorService (2 methods)

CLASS_COMMENT
invokeAny(java.util.Collection)
invokeAny(java.util.Collection, long, java.util.concurrent.TimeUnit)

ExecutorService.CLASS_COMMENT

java.util.concurrent
Interface ExecutorService

All Superinterfaces:
Executor
All Known Subinterfaces:
ScheduledExecutorService
All Known Implementing Classes:
AbstractExecutorService , ForkJoinPool , ScheduledThreadPoolExecutor , ThreadPoolExecutor

public interface ExecutorService
 extends Executor

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService . The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int) factory method:

 class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;
 
   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }
 
   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept()));
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }
 
 class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }
 
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow , if necessary, to cancel any lingering tasks:

 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }
 

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get() .

Since:
1.5

java.util.concurrent
Interface ExecutorService

All Superinterfaces:
Executor
All Known Subinterfaces:
ScheduledExecutorService
All Known Implementing Classes:
AbstractExecutorService, ScheduledThreadPoolExecutor, ThreadPoolExecutor

public interface ExecutorService
extends Executor

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int) factory method:
 class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }

   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept()));
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }

 class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }
 
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }
 

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

Since:
1.5

java.util.concurrent
Interface ExecutorService

All Superinterfaces:
Executor
All Known Subinterfaces:
ScheduledExecutorService
All Known Implementing Classes:
AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor

public interface ExecutorService
extends Executor

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int) factory method:
 class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }

   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept()));
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }

 class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }
 
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }
 

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

Since:
1.5

ExecutorService.invokeAny(java.util.Collection)

invokeAny


 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException,
                   ExecutionException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters:
tasks - the collection of tasks
Returns:
the result returned by one of the tasks
Throws:
InterruptedException - if interrupted while waiting
NullPointerException - if tasks or any element task subject to execution is of its elements are null
IllegalArgumentException - if tasks is empty
ExecutionException - if no task successfully completes
RejectedExecutionException - if tasks cannot be scheduled for execution

invokeAny

<T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException,
                   ExecutionException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters:
tasks - the collection of tasks
Returns:
the result returned by one of the tasks
Throws:
InterruptedException - if interrupted while waiting
NullPointerException - if tasks or any of its elements are null
IllegalArgumentException - if tasks is empty
ExecutionException - if no task successfully completes
RejectedExecutionException - if tasks cannot be scheduled for execution

invokeAny

<T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException,
                   ExecutionException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters:
tasks - the collection of tasks
Returns:
the result returned by one of the tasks
Throws:
InterruptedException - if interrupted while waiting
NullPointerException - if tasks or any element task subject to execution is null
IllegalArgumentException - if tasks is empty
ExecutionException - if no task successfully completes
RejectedExecutionException - if tasks cannot be scheduled for execution

ExecutorService.invokeAny(java.util.Collection, long, java.util.concurrent.TimeUnit)

invokeAny


 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                long timeout,
                TimeUnit unit)
            throws InterruptedException,
                   ExecutionException,
                   TimeoutException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters:
tasks - the collection of tasks
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
the result returned by one of the tasks.
Throws:
InterruptedException - if interrupted while waiting
NullPointerException - if tasks, or unit, or any element task subject to execution is - if tasks, any of its elements, or unit are null
TimeoutException - if the given timeout elapses before any task successfully completes
ExecutionException - if no task successfully completes
RejectedExecutionException - if tasks cannot be scheduled for execution

invokeAny

<T> T invokeAny(Collection<? extends Callable<T>> tasks,
                long timeout,
                TimeUnit unit)
            throws InterruptedException,
                   ExecutionException,
                   TimeoutException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters:
tasks - the collection of tasks
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
the result returned by one of the tasks.
Throws:
InterruptedException - if interrupted while waiting
NullPointerException - if tasks, any of its elements, or unit are null
TimeoutException - if the given timeout elapses before any task successfully completes
ExecutionException - if no task successfully completes
RejectedExecutionException - if tasks cannot be scheduled for execution

invokeAny

<T> T invokeAny(Collection<? extends Callable<T>> tasks,
                long timeout,
                TimeUnit unit)
            throws InterruptedException,
                   ExecutionException,
                   TimeoutException
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters:
tasks - the collection of tasks
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
the result returned by one of the tasks.
Throws:
InterruptedException - if interrupted while waiting
NullPointerException - if tasks, or unit, or any element task subject to execution is null
TimeoutException - if the given timeout elapses before any task successfully completes
ExecutionException - if no task successfully completes
RejectedExecutionException - if tasks cannot be scheduled for execution

java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory (New) (1 method)

CLASS_COMMENT
newThread(java.util.concurrent.ForkJoinPool)

ForkJoinPool.ForkJoinWorkerThreadFactory.CLASS_COMMENT (New)

java.util.concurrent
Interface ForkJoinPool.ForkJoinWorkerThreadFactory

Enclosing class:
ForkJoinPool

public static interface ForkJoinPool.ForkJoinWorkerThreadFactory

Factory for creating new ForkJoinWorkerThreads. A ForkJoinWorkerThreadFactory must be defined and used for ForkJoinWorkerThread subclasses that extend base functionality or initialize threads with different contexts.

ForkJoinPool.ForkJoinWorkerThreadFactory.newThread(java.util.concurrent.ForkJoinPool) (New)

newThread

ForkJoinWorkerThread newThread(ForkJoinPool pool)
Returns a new worker thread operating in the given pool.

Parameters:
pool - the pool this thread works in
Throws:
NullPointerException - if the pool is null

java.util.concurrent.ForkJoinPool.ManagedBlocker (New) (2 methods)

CLASS_COMMENT
block()
isReleasable()

ForkJoinPool.ManagedBlocker.CLASS_COMMENT (New)

java.util.concurrent
Interface ForkJoinPool.ManagedBlocker

Enclosing class:
ForkJoinPool

public static interface ForkJoinPool.ManagedBlocker

Interface for extending managed parallelism for tasks running in ForkJoinPools.

A ManagedBlocker provides two methods. Method isReleasable must return true if blocking is not necessary. Method block blocks the current thread if necessary (perhaps internally invoking isReleasable before actually blocking).

For example, here is a ManagedBlocker based on a ReentrantLock:

 class ManagedLocker implements ManagedBlocker {
   final ReentrantLock lock;
   boolean hasLock = false;
   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
   public boolean block() {
     if (!hasLock)
       lock.lock();
     return true;
   }
   public boolean isReleasable() {
     return hasLock || (hasLock = lock.tryLock());
   }
 }

ForkJoinPool.ManagedBlocker.block() (New)

block

boolean block()
              throws InterruptedException
Possibly blocks the current thread, for example waiting for a lock or condition.

Returns:
true if no additional blocking is necessary (i.e., if isReleasable would return true)
Throws:
InterruptedException - if interrupted while waiting (the method is not required to do so, but is allowed to)

ForkJoinPool.ManagedBlocker.isReleasable() (New)

isReleasable

boolean isReleasable()
Returns true if blocking is unnecessary.

java.util.concurrent.ForkJoinPool (New) (43 methods) (1 field)

CLASS_COMMENT
ForkJoinPool()
ForkJoinPool(int)
ForkJoinPool(int, java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory)
ForkJoinPool(java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory)
awaitTermination(long, java.util.concurrent.TimeUnit)
drainTasksTo(java.util.Collection)
execute(java.lang.Runnable)
execute(java.util.concurrent.ForkJoinTask)
getActiveThreadCount()
getAsyncMode()
getFactory()
getMaintainsParallelism()
getMaximumPoolSize()
getParallelism()
getPoolSize()
getQueuedSubmissionCount()
getQueuedTaskCount()
getRunningThreadCount()
getStealCount()
getUncaughtExceptionHandler()
hasQueuedSubmissions()
invoke(java.util.concurrent.ForkJoinTask)
invokeAll(java.util.Collection)
isQuiescent()
isShutdown()
isTerminated()
isTerminating()
managedBlock(java.util.concurrent.ForkJoinPool.ManagedBlocker, boolean)
newTaskFor(java.lang.Runnable,java.lang.Object)
newTaskFor(java.util.concurrent.Callable)
pollSubmission()
setAsyncMode(boolean)
setMaintainsParallelism(boolean)
setMaximumPoolSize(int)
setParallelism(int)
setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
shutdown()
shutdownNow()
submit(java.lang.Runnable)
submit(java.lang.Runnable,java.lang.Object)
submit(java.util.concurrent.Callable)
submit(java.util.concurrent.ForkJoinTask)
toString()

ForkJoinPool.CLASS_COMMENT (New)

java.util.concurrent
Class ForkJoinPool

java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
      extended by java.util.concurrent.ForkJoinPool
All Implemented Interfaces:
Executor, ExecutorService

public class ForkJoinPool
extends AbstractExecutorService

An ExecutorService for running ForkJoinTasks. A ForkJoinPool provides the entry point for submissions from non-ForkJoinTasks, as well as management and monitoring operations.

A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist). This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks). A ForkJoinPool may also be used for mixed execution of some plain Runnable- or Callable- based activities along with ForkJoinTasks. When setting async mode, a ForkJoinPool may also be appropriate for use with fine-grained tasks of any form that are never joined. Otherwise, other ExecutorService implementations are typically more appropriate choices.

A ForkJoinPool is constructed with a given target parallelism level; by default, equal to the number of available processors. Unless configured otherwise via setMaintainsParallelism(boolean), the pool attempts to maintain this number of active (or available) threads by dynamically adding, suspending, or resuming internal worker threads, even if some tasks are stalled waiting to join others. However, no such adjustments are performed in the face of blocked IO or other unmanaged synchronization. The nested ForkJoinPool.ManagedBlocker interface enables extension of the kinds of synchronization accommodated. The target parallelism level may also be changed dynamically (setParallelism(int)). The total number of threads may be limited using method setMaximumPoolSize(int), in which case it may become possible for the activities of a pool to stall due to the lack of available threads to process new tasks.

In addition to execution and lifecycle control methods, this class provides status check methods (for example getStealCount()) that are intended to aid in developing, tuning, and monitoring fork/join applications. Also, method toString() returns indications of pool state in a convenient form for informal monitoring.

Sample Usage. Normally a single ForkJoinPool is used for all parallel task execution in a program or subsystem. Otherwise, use would not usually outweigh the construction and bookkeeping overhead of creating a large set of threads. For example, a common pool could be used for the SortTasks illustrated in RecursiveAction. Because ForkJoinPool uses threads in daemon mode, there is typically no need to explicitly shutdown() such a pool upon program exit.

 static final ForkJoinPool mainPool = new ForkJoinPool();
 ...
 public void sort(long[] array) {
   mainPool.invoke(new SortTask(array, 0, array.length));
 }
 

Implementation notes: This implementation restricts the maximum number of running threads to 32767. Attempts to create pools with greater than the maximum number result in IllegalArgumentException.

This implementation rejects submitted tasks (that is, by throwing RejectedExecutionException) only when the pool is shut down.

Since:
1.7

ForkJoinPool.ForkJoinPool() (New)

ForkJoinPool

public ForkJoinPool()
Creates a ForkJoinPool with parallelism equal to Runtime.availableProcessors(), and using the default thread factory.

Throws:
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.ForkJoinPool(int) (New)

ForkJoinPool

public ForkJoinPool(int parallelism)
Creates a ForkJoinPool with the indicated parallelism level and using the default thread factory.

Parameters:
parallelism - the parallelism level
Throws:
IllegalArgumentException - if parallelism less than or equal to zero, or greater than implementation limit
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.ForkJoinPool(int, java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory) (New)

ForkJoinPool

public ForkJoinPool(int parallelism,
                    ForkJoinPool.ForkJoinWorkerThreadFactory factory)
Creates a ForkJoinPool with the given parallelism and thread factory.

Parameters:
parallelism - the parallelism level
factory - the factory for creating new threads
Throws:
IllegalArgumentException - if parallelism less than or equal to zero, or greater than implementation limit
NullPointerException - if the factory is null
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.ForkJoinPool(java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory) (New)

ForkJoinPool

public ForkJoinPool(ForkJoinPool.ForkJoinWorkerThreadFactory factory)
Creates a ForkJoinPool with parallelism equal to Runtime.availableProcessors(), and using the given thread factory.

Parameters:
factory - the factory for creating new threads
Throws:
NullPointerException - if the factory is null
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.defaultForkJoinWorkerThreadFactory (New)

defaultForkJoinWorkerThreadFactory

public static final ForkJoinPool.ForkJoinWorkerThreadFactory defaultForkJoinWorkerThreadFactory
Creates a new ForkJoinWorkerThread. This factory is used unless overridden in ForkJoinPool constructors.

ForkJoinPool.awaitTermination(long, java.util.concurrent.TimeUnit) (New)

awaitTermination

public boolean awaitTermination(long timeout,
                                TimeUnit unit)
                         throws InterruptedException
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Parameters:
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
true if this executor terminated and false if the timeout elapsed before termination
Throws:
InterruptedException - if interrupted while waiting

ForkJoinPool.drainTasksTo(java.util.Collection) (New)

drainTasksTo

protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c)
Removes all available unexecuted submitted and forked tasks from scheduling queues and adds them to the given collection, without altering their execution status. These may include artificially generated or wrapped tasks. This method is designed to be invoked only when the pool is known to be quiescent. Invocations at other times may not remove all tasks. A failure encountered while attempting to add elements to collection c may result in elements being in neither, either or both collections when the associated exception is thrown. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Parameters:
c - the collection to transfer elements into
Returns:
the number of elements transferred

ForkJoinPool.execute(java.lang.Runnable) (New)

execute

public void execute(Runnable task)
Description copied from interface: Executor
Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

Parameters:
task - the runnable task
Throws:
NullPointerException - if the task is null
RejectedExecutionException - if the task cannot be scheduled for execution

ForkJoinPool.execute(java.util.concurrent.ForkJoinTask) (New)

execute

public void execute(ForkJoinTask<?> task)
Arranges for (asynchronous) execution of the given task.

Parameters:
task - the task
Throws:
NullPointerException - if the task is null
RejectedExecutionException - if the task cannot be scheduled for execution

ForkJoinPool.getActiveThreadCount() (New)

getActiveThreadCount

public int getActiveThreadCount()
Returns an estimate of the number of threads that are currently stealing or executing tasks. This method may overestimate the number of active threads.

Returns:
the number of active threads

ForkJoinPool.getAsyncMode() (New)

getAsyncMode

public boolean getAsyncMode()
Returns true if this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined.

Returns:
true if this pool uses async mode
See Also:
setAsyncMode(boolean)

ForkJoinPool.getFactory() (New)

getFactory

public ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()
Returns the factory used for constructing new workers.

Returns:
the factory used for constructing new workers

ForkJoinPool.getMaintainsParallelism() (New)

getMaintainsParallelism

public boolean getMaintainsParallelism()
Returns true if this pool dynamically maintains its target parallelism level. If false, new threads are added only to avoid possible starvation. This setting is by default true.

Returns:
true if maintains parallelism

ForkJoinPool.getMaximumPoolSize() (New)

getMaximumPoolSize

public int getMaximumPoolSize()
Returns the maximum number of threads allowed to exist in the pool. Unless set using setMaximumPoolSize(int), the maximum is an implementation-defined value designed only to prevent runaway growth.

Returns:
the maximum

ForkJoinPool.getParallelism() (New)

getParallelism

public int getParallelism()
Returns the targeted parallelism level of this pool.

Returns:
the targeted parallelism level of this pool

ForkJoinPool.getPoolSize() (New)

getPoolSize

public int getPoolSize()
Returns the number of worker threads that have started but not yet terminated. This result returned by this method may differ from getParallelism() when threads are created to maintain parallelism when others are cooperatively blocked.

Returns:
the number of worker threads

ForkJoinPool.getQueuedSubmissionCount() (New)

getQueuedSubmissionCount

public int getQueuedSubmissionCount()
Returns an estimate of the number of tasks submitted to this pool that have not yet begun executing. This method takes time proportional to the number of submissions.

Returns:
the number of queued submissions

ForkJoinPool.getQueuedTaskCount() (New)

getQueuedTaskCount

public long getQueuedTaskCount()
Returns an estimate of the total number of tasks currently held in queues by worker threads (but not including tasks submitted to the pool that have not begun executing). This value is only an approximation, obtained by iterating across all threads in the pool. This method may be useful for tuning task granularities.

Returns:
the number of queued tasks

ForkJoinPool.getRunningThreadCount() (New)

getRunningThreadCount

public int getRunningThreadCount()
Returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization.

Returns:
the number of worker threads

ForkJoinPool.getStealCount() (New)

getStealCount

public long getStealCount()
Returns an estimate of the total number of tasks stolen from one thread's work queue by another. The reported value underestimates the actual total number of steals when the pool is not quiescent. This value may be useful for monitoring and tuning fork/join programs: in general, steal counts should be high enough to keep threads busy, but low enough to avoid overhead and contention across threads.

Returns:
the number of steals

ForkJoinPool.getUncaughtExceptionHandler() (New)

getUncaughtExceptionHandler

public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
Returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.

Returns:
the handler, or null if none

ForkJoinPool.hasQueuedSubmissions() (New)

hasQueuedSubmissions

public boolean hasQueuedSubmissions()
Returns true if there are any tasks submitted to this pool that have not yet begun executing.

Returns:
true if there are any queued submissions

ForkJoinPool.invoke(java.util.concurrent.ForkJoinTask) (New)

invoke

public <T> T invoke(ForkJoinTask<T> task)
Performs the given task, returning its result upon completion.

Parameters:
task - the task
Returns:
the task's result
Throws:
NullPointerException - if the task is null
RejectedExecutionException - if the task cannot be scheduled for execution

ForkJoinPool.invokeAll(java.util.Collection) (New)

invokeAll

public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
Description copied from interface: ExecutorService
Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

Specified by:
invokeAll in interface ExecutorService
Overrides:
invokeAll in class AbstractExecutorService
Parameters:
tasks - the collection of tasks
Returns:
A list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed.
Throws:
NullPointerException - if tasks or any of its elements are null
RejectedExecutionException - if any task cannot be scheduled for execution

ForkJoinPool.isQuiescent() (New)

isQuiescent

public boolean isQuiescent()
Returns true if all worker threads are currently idle. An idle worker is one that cannot obtain a task to execute because none are available to steal from other threads, and there are no pending submissions to the pool. This method is conservative; it might not return true immediately upon idleness of all threads, but will eventually become true if threads remain inactive.

Returns:
true if all threads are currently idle

ForkJoinPool.isShutdown() (New)

isShutdown

public boolean isShutdown()
Returns true if this pool has been shut down.

Returns:
true if this pool has been shut down

ForkJoinPool.isTerminated() (New)

isTerminated

public boolean isTerminated()
Returns true if all tasks have completed following shut down.

Returns:
true if all tasks have completed following shut down

ForkJoinPool.isTerminating() (New)

isTerminating

public boolean isTerminating()
Returns true if the process of termination has commenced but not yet completed. This method may be useful for debugging. A return of true reported a sufficient period after shutdown may indicate that submitted tasks have ignored or suppressed interruption, causing this executor not to properly terminate.

Returns:
true if terminating but not yet terminated

ForkJoinPool.managedBlock(java.util.concurrent.ForkJoinPool.ManagedBlocker, boolean) (New)

managedBlock

public static void managedBlock(ForkJoinPool.ManagedBlocker blocker,
                                boolean maintainParallelism)
                         throws InterruptedException
Blocks in accord with the given blocker. If the current thread is a ForkJoinWorkerThread, this method possibly arranges for a spare thread to be activated if necessary to ensure parallelism while the current thread is blocked.

If maintainParallelism is true and the pool supports it (getMaintainsParallelism()), this method attempts to maintain the pool's nominal parallelism. Otherwise it activates a thread only if necessary to avoid complete starvation. This option may be preferable when blockages use timeouts, or are almost always brief.

If the caller is not a ForkJoinTask, this method is behaviorally equivalent to

 while (!blocker.isReleasable())
   if (blocker.block())
     return;
 
If the caller is a ForkJoinTask, then the pool may first be expanded to ensure parallelism, and later adjusted.

Parameters:
blocker - the blocker
maintainParallelism - if true and supported by this pool, attempt to maintain the pool's nominal parallelism; otherwise activate a thread only if necessary to avoid complete starvation.
Throws:
InterruptedException - if blocker.block did so

ForkJoinPool.newTaskFor(java.lang.Runnable,java.lang.Object) (New)

newTaskFor

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable,
                                           T value)
Description copied from class: AbstractExecutorService
Returns a RunnableFuture for the given runnable and default value.

Overrides:
newTaskFor in class AbstractExecutorService
Parameters:
runnable - the runnable task being wrapped
value - the default value for the returned future
Returns:
a RunnableFuture which when run will run the underlying runnable and which, as a Future, will yield the given value as its result and provide for cancellation of the underlying task.

ForkJoinPool.newTaskFor(java.util.concurrent.Callable) (New)

newTaskFor

protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable)
Description copied from class: AbstractExecutorService
Returns a RunnableFuture for the given callable task.

Overrides:
newTaskFor in class AbstractExecutorService
Parameters:
callable - the callable task being wrapped
Returns:
a RunnableFuture which when run will call the underlying callable and which, as a Future, will yield the callable's result as its result and provide for cancellation of the underlying task.

ForkJoinPool.pollSubmission() (New)

pollSubmission

protected ForkJoinTask<?> pollSubmission()
Removes and returns the next unexecuted submission if one is available. This method may be useful in extensions to this class that re-assign work in systems with multiple pools.

Returns:
the next submission, or null if none

ForkJoinPool.setAsyncMode(boolean) (New)

setAsyncMode

public boolean setAsyncMode(boolean async)
Establishes local first-in-first-out scheduling mode for forked tasks that are never joined. This mode may be more appropriate than default locally stack-based mode in applications in which worker threads only process asynchronous tasks. This method is designed to be invoked only when the pool is quiescent, and typically only before any tasks are submitted. The effects of invocations at other times may be unpredictable.

Parameters:
async - if true, use locally FIFO scheduling
Returns:
the previous mode
See Also:
getAsyncMode()

ForkJoinPool.setMaintainsParallelism(boolean) (New)

setMaintainsParallelism

public void setMaintainsParallelism(boolean enable)
Sets whether this pool dynamically maintains its target parallelism level. If false, new threads are added only to avoid possible starvation.

Parameters:
enable - true to maintain parallelism

ForkJoinPool.setMaximumPoolSize(int) (New)

setMaximumPoolSize

public void setMaximumPoolSize(int newMax)
Sets the maximum number of threads allowed to exist in the pool. The given value should normally be greater than or equal to the parallelism level. Setting this value has no effect on current pool size. It controls construction of new threads.

Throws:
IllegalArgumentException - if negative or greater than internal implementation limit

ForkJoinPool.setParallelism(int) (New)

setParallelism

public void setParallelism(int parallelism)
Sets the target parallelism level of this pool.

Parameters:
parallelism - the target parallelism
Throws:
IllegalArgumentException - if parallelism less than or equal to zero or greater than maximum size bounds
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) (New)

setUncaughtExceptionHandler

public Thread.UncaughtExceptionHandler setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h)
Sets the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. Unless set, the current default or ThreadGroup handler is used as handler.

Parameters:
h - the new handler
Returns:
the old handler, or null if none
Throws:
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.shutdown() (New)

shutdown

public void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down. Tasks that are in the process of being submitted concurrently during the course of this method may or may not be rejected.

Throws:
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.shutdownNow() (New)

shutdownNow

public List<Runnable> shutdownNow()
Attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. Tasks that are in the process of being submitted or executed concurrently during the course of this method may or may not be rejected. This method cancels both existing and unexecuted tasks, in order to permit termination in the presence of task dependencies. So the method always returns an empty list (unlike the case for some other Executors).

Returns:
an empty list
Throws:
SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

ForkJoinPool.submit(java.lang.Runnable) (New)

submit

public ForkJoinTask<?> submit(Runnable task)
Description copied from interface: ExecutorService
Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return null upon successful completion.

Specified by:
submit in interface ExecutorService
Overrides:
submit in class AbstractExecutorService
Parameters:
task - the task to submit
Returns:
a Future representing pending completion of the task
Throws:
NullPointerException - if the task is null
RejectedExecutionException - if the task cannot be scheduled for execution

ForkJoinPool.submit(java.lang.Runnable,java.lang.Object) (New)

submit

public <T> ForkJoinTask<T> submit(Runnable task,
                                  T result)
Description copied from interface: ExecutorService
Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return the given result upon successful completion.

Specified by:
submit in interface ExecutorService
Overrides:
submit in class AbstractExecutorService
Parameters:
task - the task to submit
result - the result to return
Returns:
a Future representing pending completion of the task
Throws:
NullPointerException - if the task is null
RejectedExecutionException - if the task cannot be scheduled for execution

ForkJoinPool.submit(java.util.concurrent.Callable) (New)

submit

public <T> ForkJoinTask<T> submit(Callable<T> task)
Description copied from interface: ExecutorService
Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future's get method will return the task's result upon successful completion.

If you would like to immediately block waiting for a task, you can use constructions of the form result = exec.submit(aCallable).get();

Note: The Executors class includes a set of methods that can convert some other common closure-like objects, for example, PrivilegedAction to Callable form so they can be submitted.

Specified by:
submit in interface ExecutorService
Overrides:
submit in class AbstractExecutorService
Parameters:
task - the task to submit
Returns:
a Future representing pending completion of the task
Throws:
NullPointerException - if the task is null
RejectedExecutionException - if the task cannot be scheduled for execution

ForkJoinPool.submit(java.util.concurrent.ForkJoinTask) (New)

submit

public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task)
Submits a ForkJoinTask for execution.

Parameters:
task - the task to submit
Returns:
the task
Throws:
NullPointerException - if the task is null
RejectedExecutionException - if the task cannot be scheduled for execution

ForkJoinPool.toString() (New)

toString

public String toString()
Returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts.

Overrides:
toString in class Object
Returns:
a string identifying this pool, as well as its state

java.util.concurrent.ForkJoinTask (New) (37 methods)

CLASS_COMMENT
ForkJoinTask()
adapt(java.lang.Runnable)
adapt(java.lang.Runnable,java.lang.Object)
adapt(java.util.concurrent.Callable)
cancel(boolean)
complete(java.lang.Object)
completeExceptionally(java.lang.Throwable)
exec()
fork()
get()
get(long, java.util.concurrent.TimeUnit)
getException()
getPool()
getQueuedTaskCount()
getRawResult()
getSurplusQueuedTaskCount()
helpJoin()
helpQuiesce()
inForkJoinPool()
invoke()
invokeAll(java.util.Collection)
invokeAll(java.util.concurrent.ForkJoinTask, java.util.concurrent.ForkJoinTask)
invokeAll(java.util.concurrent.ForkJoinTask...)
isCancelled()
isCompletedAbnormally()
isCompletedNormally()
isDone()
join()
peekNextLocalTask()
pollNextLocalTask()
pollTask()
quietlyHelpJoin()
quietlyInvoke()
quietlyJoin()
reinitialize()
setRawResult(java.lang.Object)
tryUnfork()

ForkJoinTask.CLASS_COMMENT (New)

java.util.concurrent
Class ForkJoinTask<V>

java.lang.Object
  extended by java.util.concurrent.ForkJoinTask<V>
All Implemented Interfaces:
Serializable, Future<V>
Direct Known Subclasses:
RecursiveAction, RecursiveTask

public abstract class ForkJoinTask<V>
extends Object
implements Future<V>, Serializable

Abstract base class for tasks that run within a ForkJoinPool. A ForkJoinTask is a thread-like entity that is much lighter weight than a normal thread. Huge numbers of tasks and subtasks may be hosted by a small number of actual threads in a ForkJoinPool, at the price of some usage limitations.

A "main" ForkJoinTask begins execution when submitted to a ForkJoinPool. Once started, it will usually in turn start other subtasks. As indicated by the name of this class, many programs using ForkJoinTask employ only methods fork() and join(), or derivatives such as invokeAll(java.util.concurrent.ForkJoinTask, java.util.concurrent.ForkJoinTask). However, this class also provides a number of other methods that can come into play in advanced usages, as well as extension mechanics that allow support of new forms of fork/join processing.

A ForkJoinTask is a lightweight form of Future. The efficiency of ForkJoinTasks stems from a set of restrictions (that are only partially statically enforceable) reflecting their intended use as computational tasks calculating pure functions or operating on purely isolated objects. The primary coordination mechanisms are fork(), that arranges asynchronous execution, and join(), that doesn't proceed until the task's result has been computed. Computations should avoid synchronized methods or blocks, and should minimize other blocking synchronization apart from joining other tasks or using synchronizers such as Phasers that are advertised to cooperate with fork/join scheduling. Tasks should also not perform blocking IO, and should ideally access variables that are completely independent of those accessed by other running tasks. Minor breaches of these restrictions, for example using shared output streams, may be tolerable in practice, but frequent use may result in poor performance, and the potential to indefinitely stall if the number of threads not waiting for IO or other external synchronization becomes exhausted. This usage restriction is in part enforced by not permitting checked exceptions such as IOExceptions to be thrown. However, computations may still encounter unchecked exceptions, that are rethrown to callers attempting to join them. These exceptions may additionally include RejectedExecutionException stemming from internal resource exhaustion, such as failure to allocate internal task queues.

The primary method for awaiting completion and extracting results of a task is join(), but there are several variants: The Future.get() methods support interruptible and/or timed waits for completion and report results using Future conventions. Method helpJoin() enables callers to actively execute other tasks while awaiting joins, which is sometimes more efficient but only applies when all subtasks are known to be strictly tree-structured. Method invoke() is semantically equivalent to fork(); join() but always attempts to begin execution in the current thread. The "quiet" forms of these methods do not extract results or report exceptions. These may be useful when a set of tasks are being executed, and you need to delay processing of results or exceptions until all complete. Method invokeAll (available in multiple versions) performs the most common form of parallel invocation: forking a set of tasks and joining them all.

The execution status of tasks may be queried at several levels of detail: isDone() is true if a task completed in any way (including the case where a task was cancelled without executing); isCompletedNormally() is true if a task completed without cancellation or encountering an exception; isCancelled() is true if the task was cancelled (in which case getException() returns a CancellationException); and isCompletedAbnormally() is true if a task was either cancelled or encountered an exception, in which case getException() will return either the encountered exception or CancellationException.

The ForkJoinTask class is not usually directly subclassed. Instead, you subclass one of the abstract classes that support a particular style of fork/join processing, typically RecursiveAction for computations that do not return results, or RecursiveTask for those that do. Normally, a concrete ForkJoinTask subclass declares fields comprising its parameters, established in a constructor, and then defines a compute method that somehow uses the control methods supplied by this base class. While these methods have public access (to allow instances of different task subclasses to call each other's methods), some of them may only be called from within other ForkJoinTasks (as may be determined using method inForkJoinPool()). Attempts to invoke them in other contexts result in exceptions or errors, possibly including ClassCastException.

Most base support methods are final, to prevent overriding of implementations that are intrinsically tied to the underlying lightweight task scheduling framework. Developers creating new basic styles of fork/join processing should minimally implement protected methods exec(), setRawResult(V), and getRawResult(), while also introducing an abstract computational method that can be implemented in its subclasses, possibly relying on other protected methods provided by this class.

ForkJoinTasks should perform relatively small amounts of computation. Large tasks should be split into smaller subtasks, usually via recursive decomposition. As a very rough rule of thumb, a task should perform more than 100 and less than 10000 basic computational steps. If tasks are too big, then parallelism cannot improve throughput. If too small, then memory and internal task maintenance overhead may overwhelm processing.

This class provides adapt methods for Runnable and Callable, that may be of use when mixing execution of ForkJoinTasks with other kinds of tasks. When all tasks are of this form, consider using a pool in async mode.

ForkJoinTasks are Serializable, which enables them to be used in extensions such as remote execution frameworks. It is sensible to serialize tasks only before or after, but not during, execution. Serialization is not relied on during execution itself.

Since:
1.7
See Also:
Serialized Form

ForkJoinTask.ForkJoinTask() (New)

ForkJoinTask

public ForkJoinTask()

ForkJoinTask.adapt(java.lang.Runnable) (New)

adapt

public static ForkJoinTask<?> adapt(Runnable runnable)
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns a null result upon join().

Parameters:
runnable - the runnable action
Returns:
the task

ForkJoinTask.adapt(java.lang.Runnable,java.lang.Object) (New)

adapt

public static <T> ForkJoinTask<T> adapt(Runnable runnable,
                                        T result)
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns the given result upon join().

Parameters:
runnable - the runnable action
result - the result upon completion
Returns:
the task

ForkJoinTask.adapt(java.util.concurrent.Callable) (New)

adapt

public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable)
Returns a new ForkJoinTask that performs the call method of the given Callable as its action, and returns its result upon join(), translating any checked exceptions encountered into RuntimeException.

Parameters:
callable - the callable action
Returns:
the task

ForkJoinTask.cancel(boolean) (New)

cancel

public boolean cancel(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, execution of this task is suppressed, isCancelled() will report true, and join() will result in a CancellationException being thrown.

This method may be overridden in subclasses, but if so, must still ensure that these minimal properties hold. In particular, the cancel method itself must not throw exceptions.

This method is designed to be invoked by other tasks. To terminate the current task, you can just return or throw an unchecked exception from its computation method, or invoke completeExceptionally(java.lang.Throwable).

Specified by:
cancel in interface Future<V>
Parameters:
mayInterruptIfRunning - this value is ignored in the default implementation because tasks are not cancelled via interruption
Returns:
true if this task is now cancelled

ForkJoinTask.complete(java.lang.Object) (New)

complete

public void complete(V value)
Completes this task, and if not already aborted or cancelled, returning a null result upon join and related operations. This method may be used to provide results for asynchronous tasks, or to provide alternative handling for tasks that would not otherwise complete normally. Its use in other situations is discouraged. This method is overridable, but overridden versions must invoke super implementation to maintain guarantees.

Parameters:
value - the result value for this task

ForkJoinTask.completeExceptionally(java.lang.Throwable) (New)

completeExceptionally

public void completeExceptionally(Throwable ex)
Completes this task abnormally, and if not already aborted or cancelled, causes it to throw the given exception upon join and related operations. This method may be used to induce exceptions in asynchronous tasks, or to force completion of tasks that would not otherwise complete. Its use in other situations is discouraged. This method is overridable, but overridden versions must invoke super implementation to maintain guarantees.

Parameters:
ex - the exception to throw. If this exception is not a RuntimeException or Error, the actual exception thrown will be a RuntimeException with cause ex.

ForkJoinTask.exec() (New)

exec

protected abstract boolean exec()
Immediately performs the base action of this task. This method is designed to support extensions, and should not in general be called otherwise. The return value controls whether this task is considered to be done normally. It may return false in asynchronous actions that require explicit invocations of complete(V) to become joinable. It may also throw an (unchecked) exception to indicate abnormal exit.

Returns:
true if completed normally

ForkJoinTask.fork() (New)

fork

public final ForkJoinTask<V> fork()
Arranges to asynchronously execute this task. While it is not necessarily enforced, it is a usage error to fork a task more than once unless it has completed and been reinitialized. Subsequent modifications to the state of this task or any data it operates on are not necessarily consistently observable by any thread other than the one executing it unless preceded by a call to join() or related methods, or a call to isDone() returning true.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
this, to simplify usage

ForkJoinTask.get() (New)

get

public final V get()
            throws InterruptedException,
                   ExecutionException
Description copied from interface: Future
Waits if necessary for the computation to complete, and then retrieves its result.

Specified by:
get in interface Future<V>
Returns:
the computed result
Throws:
InterruptedException - if the current thread was interrupted while waiting
ExecutionException - if the computation threw an exception

ForkJoinTask.get(long, java.util.concurrent.TimeUnit) (New)

get

public final V get(long timeout,
                   TimeUnit unit)
            throws InterruptedException,
                   ExecutionException,
                   TimeoutException
Description copied from interface: Future
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Specified by:
get in interface Future<V>
Parameters:
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
the computed result
Throws:
InterruptedException - if the current thread was interrupted while waiting
ExecutionException - if the computation threw an exception
TimeoutException - if the wait timed out

ForkJoinTask.getException() (New)

getException

public final Throwable getException()
Returns the exception thrown by the base computation, or a CancellationException if cancelled, or null if none or if the method has not yet completed.

Returns:
the exception, or null if none

ForkJoinTask.getPool() (New)

getPool

public static ForkJoinPool getPool()
Returns the pool hosting the current task execution, or null if this task is executing outside of any ForkJoinPool.

Returns:
the pool, or null if none
See Also:
inForkJoinPool()

ForkJoinTask.getQueuedTaskCount() (New)

getQueuedTaskCount

public static int getQueuedTaskCount()
Returns an estimate of the number of tasks that have been forked by the current worker thread but not yet executed. This value may be useful for heuristic decisions about whether to fork other tasks.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
the number of tasks

ForkJoinTask.getRawResult() (New)

getRawResult

public abstract V getRawResult()
Returns the result that would be returned by join(), even if this task completed abnormally, or null if this task is not known to have been completed. This method is designed to aid debugging, as well as to support extensions. Its use in any other context is discouraged.

Returns:
the result, or null if not completed

ForkJoinTask.getSurplusQueuedTaskCount() (New)

getSurplusQueuedTaskCount

public static int getSurplusQueuedTaskCount()
Returns an estimate of how many more locally queued tasks are held by the current worker thread than there are other worker threads that might steal them. This value may be useful for heuristic decisions about whether to fork other tasks. In many usages of ForkJoinTasks, at steady state, each worker should aim to maintain a small constant surplus (for example, 3) of tasks, and to process computations locally if this threshold is exceeded.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
the surplus number of tasks, which may be negative

ForkJoinTask.helpJoin() (New)

helpJoin

public final V helpJoin()
Possibly executes other tasks until this task is done, then returns the result of the computation. This method may be more efficient than join, but is only applicable when there are no potential dependencies between continuation of the current task and that of any other task that might be executed while helping. (This usually holds for pure divide-and-conquer tasks).

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
the computed result

ForkJoinTask.helpQuiesce() (New)

helpQuiesce

public static void helpQuiesce()
Possibly executes tasks until the pool hosting the current task is quiescent. This method may be of use in designs in which many tasks are forked, but none are explicitly joined, instead executing them until all are processed.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

ForkJoinTask.inForkJoinPool() (New)

inForkJoinPool

public static boolean inForkJoinPool()
Returns true if the current thread is executing as a ForkJoinPool computation.

Returns:
true if the current thread is executing as a ForkJoinPool computation, or false otherwise

ForkJoinTask.invoke() (New)

invoke

public final V invoke()
Commences performing this task, awaits its completion if necessary, and return its result, or throws an (unchecked) exception if the underlying computation did so.

Returns:
the computed result

ForkJoinTask.invokeAll(java.util.Collection) (New)

invokeAll

public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks)
Forks all tasks in the specified collection, returning when isDone holds for each task or an (unchecked) exception is encountered. If any task encounters an exception, others may be, but are not guaranteed to be, cancelled. If more than one task encounters an exception, then this method throws any one of these exceptions. The individual status of each task may be checked using getException() and related methods. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Parameters:
tasks - the collection of tasks
Returns:
the tasks argument, to simplify usage
Throws:
NullPointerException - if tasks or any element are null

ForkJoinTask.invokeAll(java.util.concurrent.ForkJoinTask, java.util.concurrent.ForkJoinTask) (New)

invokeAll

public static void invokeAll(ForkJoinTask<?> t1,
                             ForkJoinTask<?> t2)
Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown. If either task encounters an exception, the other one may be, but is not guaranteed to be, cancelled. If both tasks throw an exception, then this method throws one of them. The individual status of each task may be checked using getException() and related methods.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Parameters:
t1 - the first task
t2 - the second task
Throws:
NullPointerException - if any task is null

ForkJoinTask.invokeAll(java.util.concurrent.ForkJoinTask...) (New)

invokeAll

public static void invokeAll(ForkJoinTask<?>... tasks)
Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown. If any task encounters an exception, others may be, but are not guaranteed to be, cancelled. If more than one task encounters an exception, then this method throws any one of these exceptions. The individual status of each task may be checked using getException() and related methods.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Parameters:
tasks - the tasks
Throws:
NullPointerException - if any task is null

ForkJoinTask.isCancelled() (New)

isCancelled

public final boolean isCancelled()
Description copied from interface: Future
Returns true if this task was cancelled before it completed normally.

Specified by:
isCancelled in interface Future<V>
Returns:
true if this task was cancelled before it completed

ForkJoinTask.isCompletedAbnormally() (New)

isCompletedAbnormally

public final boolean isCompletedAbnormally()
Returns true if this task threw an exception or was cancelled.

Returns:
true if this task threw an exception or was cancelled

ForkJoinTask.isCompletedNormally() (New)

isCompletedNormally

public final boolean isCompletedNormally()
Returns true if this task completed without throwing an exception and was not cancelled.

Returns:
true if this task completed without throwing an exception and was not cancelled

ForkJoinTask.isDone() (New)

isDone

public final boolean isDone()
Description copied from interface: Future
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

Specified by:
isDone in interface Future<V>
Returns:
true if this task completed

ForkJoinTask.join() (New)

join

public final V join()
Returns the result of the computation when it is done. This method differs from get() in that abnormal completion results in RuntimeException or Error, not ExecutionException.

Returns:
the computed result

ForkJoinTask.peekNextLocalTask() (New)

peekNextLocalTask

protected static ForkJoinTask<?> peekNextLocalTask()
Returns, but does not unschedule or execute, a task queued by the current thread but not yet executed, if one is immediately available. There is no guarantee that this task will actually be polled or executed next. Conversely, this method may return null even if a task exists but cannot be accessed without contention with other threads. This method is designed primarily to support extensions, and is unlikely to be useful otherwise.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
the next task, or null if none are available

ForkJoinTask.pollNextLocalTask() (New)

pollNextLocalTask

protected static ForkJoinTask<?> pollNextLocalTask()
Unschedules and returns, without executing, the next task queued by the current thread but not yet executed. This method is designed primarily to support extensions, and is unlikely to be useful otherwise.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
the next task, or null if none are available

ForkJoinTask.pollTask() (New)

pollTask

protected static ForkJoinTask<?> pollTask()
Unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if one is available, or if not available, a task that was forked by some other thread, if available. Availability may be transient, so a null result does not necessarily imply quiescence of the pool this task is operating in. This method is designed primarily to support extensions, and is unlikely to be useful otherwise.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
a task, or null if none are available

ForkJoinTask.quietlyHelpJoin() (New)

quietlyHelpJoin

public final void quietlyHelpJoin()
Possibly executes other tasks until this task is done. This method may be useful when processing collections of tasks when some have been cancelled or otherwise known to have aborted.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

ForkJoinTask.quietlyInvoke() (New)

quietlyInvoke

public final void quietlyInvoke()
Commences performing this task and awaits its completion if necessary, without returning its result or throwing an exception. This method may be useful when processing collections of tasks when some have been cancelled or otherwise known to have aborted.

ForkJoinTask.quietlyJoin() (New)

quietlyJoin

public final void quietlyJoin()
Joins this task, without returning its result or throwing an exception. This method may be useful when processing collections of tasks when some have been cancelled or otherwise known to have aborted.

ForkJoinTask.reinitialize() (New)

reinitialize

public void reinitialize()
Resets the internal bookkeeping state of this task, allowing a subsequent fork. This method allows repeated reuse of this task, but only if reuse occurs when this task has either never been forked, or has been forked, then completed and all outstanding joins of this task have also completed. Effects under any other usage conditions are not guaranteed. This method may be useful when executing pre-constructed trees of subtasks in loops.

ForkJoinTask.setRawResult(java.lang.Object) (New)

setRawResult

protected abstract void setRawResult(V value)
Forces the given value to be returned as a result. This method is designed to support extensions, and should not in general be called otherwise.

Parameters:
value - the value

ForkJoinTask.tryUnfork() (New)

tryUnfork

public boolean tryUnfork()
Tries to unschedule this task for execution. This method will typically succeed if this task is the most recently forked task by the current thread, and has not commenced executing in another thread. This method may be useful when arranging alternative local processing of tasks that could have been, but were not, stolen.

This method may be invoked only from within ForkJoinTask computations (as may be determined using method inForkJoinPool()). Attempts to invoke in other contexts result in exceptions or errors, possibly including ClassCastException.

Returns:
true if unforked

java.util.concurrent.ForkJoinWorkerThread (New) (6 methods)

CLASS_COMMENT
ForkJoinWorkerThread(java.util.concurrent.ForkJoinPool)
getPool()
getPoolIndex()
onStart()
onTermination(java.lang.Throwable)
run()

ForkJoinWorkerThread.CLASS_COMMENT (New)

java.util.concurrent
Class ForkJoinWorkerThread

java.lang.Object
  extended by java.lang.Thread
      extended by java.util.concurrent.ForkJoinWorkerThread
All Implemented Interfaces:
Runnable

public class ForkJoinWorkerThread
extends Thread

A thread managed by a ForkJoinPool. This class is subclassable solely for the sake of adding functionality -- there are no overridable methods dealing with scheduling or execution. However, you can override initialization and termination methods surrounding the main task processing loop. If you do create such a subclass, you will also need to supply a custom ForkJoinPool.ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.

Since:
1.7

ForkJoinWorkerThread.ForkJoinWorkerThread(java.util.concurrent.ForkJoinPool) (New)

ForkJoinWorkerThread

protected ForkJoinWorkerThread(ForkJoinPool pool)
Creates a ForkJoinWorkerThread operating in the given pool.

Parameters:
pool - the pool this thread works in
Throws:
NullPointerException - if pool is null

ForkJoinWorkerThread.getPool() (New)

getPool

public ForkJoinPool getPool()
Returns the pool hosting this thread.

Returns:
the pool

ForkJoinWorkerThread.getPoolIndex() (New)

getPoolIndex

public int getPoolIndex()
Returns the index number of this thread in its pool. The returned value ranges from zero to the maximum number of threads (minus one) that have ever been created in the pool. This method may be useful for applications that track status or collect results per-worker rather than per-task.

Returns:
the index number

ForkJoinWorkerThread.onStart() (New)

onStart

protected void onStart()
Initializes internal state after construction but before processing any tasks. If you override this method, you must invoke super.onStart() at the beginning of the method. Initialization requires care: Most fields must have legal default values, to ensure that attempted accesses from other threads work correctly even before this thread starts processing tasks.

ForkJoinWorkerThread.onTermination(java.lang.Throwable) (New)

onTermination

protected void onTermination(Throwable exception)
Performs cleanup associated with termination of this worker thread. If you override this method, you must invoke super.onTermination at the end of the overridden method.

Parameters:
exception - the exception causing this thread to abort due to an unrecoverable error, or null if completed normally

ForkJoinWorkerThread.run() (New)

run

public void run()
This method is required to be public, but should never be called explicitly. It performs the main run loop to execute ForkJoinTasks.

Specified by:
run in interface Runnable
Overrides:
run in class Thread

java.util.concurrent.Future

Future.CLASS_COMMENT

java.util.concurrent
Interface Future<V>

Type Parameters:
V - The result type returned by this Future's get method
All Known Subinterfaces:
RunnableFuture<V>, RunnableScheduledFuture<V>, ScheduledFuture<V>
All Known Implementing Classes:
ForkJoinTask FutureTask , FutureTask , RecursiveAction , RecursiveTask

public interface Future<V>

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

Sample Usage (Note that the following classes are all made-up.)


 interface ArchiveSearcher { String search(String target); }
 class App {
   ExecutorService executor = ...
   ArchiveSearcher searcher = ...
   void showSearch(final String target)
       throws InterruptedException {
     Future<String> future
       = executor.submit(new Callable<String>() {
         public String call() {
             return searcher.search(target);
         }});
     displayOtherThings(); // do other things while searching
     try {
       displayText(future.get()); // use future
     } catch (ExecutionException ex) { cleanup(); return; }
   }
 }
 
The FutureTask class is an implementation of Future that implements Runnable , and so may be executed by an Executor . For example, the above construction with submit could be replaced by:

     FutureTask<String> future =
       new FutureTask<String>(new Callable<String>() {
         public String call() {
           return searcher.search(target);
       }});
     executor.execute(future);
 

Memory consistency effects: Actions taken by the asynchronous computation happen-before actions following the corresponding Future.get() in another thread.

Since:
1.5
See Also:
FutureTask , Executor

java.util.concurrent
Interface Future<V>

Type Parameters:
V - The result type returned by this Future's get method
All Known Subinterfaces:
RunnableFuture<V>, RunnableScheduledFuture<V>, ScheduledFuture<V>
All Known Implementing Classes:
FutureTask

public interface Future<V>

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

Sample Usage (Note that the following classes are all made-up.)

 interface ArchiveSearcher { String search(String target); }
 class App {
   ExecutorService executor = ...
   ArchiveSearcher searcher = ...
   void showSearch(final String target)
       throws InterruptedException {
     Future<String> future
       = executor.submit(new Callable<String>() {
         public String call() {
             return searcher.search(target);
         }});
     displayOtherThings(); // do other things while searching
     try {
       displayText(future.get()); // use future
     } catch (ExecutionException ex) { cleanup(); return; }
   }
 }
 
The FutureTask class is an implementation of Future that implements Runnable, and so may be executed by an Executor. For example, the above construction with submit could be replaced by:
     FutureTask<String> future =
       new FutureTask<String>(new Callable<String>() {
         public String call() {
           return searcher.search(target);
       }});
     executor.execute(future);
 

Memory consistency effects: Actions taken by the asynchronous computation happen-before actions following the corresponding Future.get() in another thread.

Since:
1.5
See Also:
FutureTask, Executor

java.util.concurrent
Interface Future<V>

Type Parameters:
V - The result type returned by this Future's get method
All Known Subinterfaces:
RunnableFuture<V>, RunnableScheduledFuture<V>, ScheduledFuture<V>
All Known Implementing Classes:
ForkJoinTask, FutureTask, RecursiveAction, RecursiveTask

public interface Future<V>

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

Sample Usage (Note that the following classes are all made-up.)

 interface ArchiveSearcher { String search(String target); }
 class App {
   ExecutorService executor = ...
   ArchiveSearcher searcher = ...
   void showSearch(final String target)
       throws InterruptedException {
     Future<String> future
       = executor.submit(new Callable<String>() {
         public String call() {
             return searcher.search(target);
         }});
     displayOtherThings(); // do other things while searching
     try {
       displayText(future.get()); // use future
     } catch (ExecutionException ex) { cleanup(); return; }
   }
 }
 
The FutureTask class is an implementation of Future that implements Runnable, and so may be executed by an Executor. For example, the above construction with submit could be replaced by:
     FutureTask<String> future =
       new FutureTask<String>(new Callable<String>() {
         public String call() {
           return searcher.search(target);
       }});
     executor.execute(future);
 

Memory consistency effects: Actions taken by the asynchronous computation happen-before actions following the corresponding Future.get() in another thread.

Since:
1.5
See Also:
FutureTask, Executor

java.util.concurrent.LinkedTransferQueue (New) (22 methods)

CLASS_COMMENT
LinkedTransferQueue()
LinkedTransferQueue(java.util.Collection)
add(java.lang.Object)
drainTo(java.util.Collection)
drainTo(java.util.Collection, int)
getWaitingConsumerCount()
hasWaitingConsumer()
isEmpty()
iterator()
offer(java.lang.Object)
offer(java.lang.Object,long,java.util.concurrent.TimeUnit)
peek()
poll()
poll(long, java.util.concurrent.TimeUnit)
put(java.lang.Object)
remainingCapacity()
remove(java.lang.Object)
size()
take()
transfer(java.lang.Object)
tryTransfer(java.lang.Object)
tryTransfer(java.lang.Object,long,java.util.concurrent.TimeUnit)

LinkedTransferQueue.CLASS_COMMENT (New)

java.util.concurrent
Class LinkedTransferQueue<E>

java.lang.Object
  extended by java.util.AbstractCollection<E>
      extended by java.util.AbstractQueue<E>
          extended by java.util.concurrent.LinkedTransferQueue<E>
Type Parameters:
E - the type of elements held in this collection
All Implemented Interfaces:
Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, TransferQueue<E>, Queue<E>

public class LinkedTransferQueue<E>
extends AbstractQueue<E>
implements TransferQueue<E>, Serializable

An unbounded TransferQueue based on linked nodes. This queue orders elements FIFO (first-in-first-out) with respect to any given producer. The head of the queue is that element that has been on the queue the longest time for some producer. The tail of the queue is that element that has been on the queue the shortest time for some producer.

Beware that, unlike in most collections, the size method is NOT a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires a traversal of the elements.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a LinkedTransferQueue happen-before actions subsequent to the access or removal of that element from the LinkedTransferQueue in another thread.

This class is a member of the Java Collections Framework.

Since:
1.7
See Also:
Serialized Form

LinkedTransferQueue.LinkedTransferQueue() (New)

LinkedTransferQueue

public LinkedTransferQueue()
Creates an initially empty LinkedTransferQueue.

LinkedTransferQueue.LinkedTransferQueue(java.util.Collection) (New)

LinkedTransferQueue

public LinkedTransferQueue(Collection<? extends E> c)
Creates a LinkedTransferQueue initially containing the elements of the given collection, added in traversal order of the collection's iterator.

Parameters:
c - the collection of elements to initially contain
Throws:
NullPointerException - if the specified collection or any of its elements are null

LinkedTransferQueue.add(java.lang.Object) (New)

add

public boolean add(E e)
Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never throw IllegalStateException or return false.

Specified by:
add in interface Collection<E>
Specified by:
add in interface BlockingQueue<E>
Specified by:
add in interface Queue<E>
Overrides:
add in class AbstractQueue<E>
Parameters:
e - the element to add
Returns:
true (as specified by Collection.add(E))
Throws:
NullPointerException - if the specified element is null

LinkedTransferQueue.drainTo(java.util.Collection) (New)

drainTo

public int drainTo(Collection<? super E> c)
Description copied from interface: BlockingQueue
Removes all available elements from this queue and adds them to the given collection. This operation may be more efficient than repeatedly polling this queue. A failure encountered while attempting to add elements to collection c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Specified by:
drainTo in interface BlockingQueue<E>
Parameters:
c - the collection to transfer elements into
Returns:
the number of elements transferred
Throws:
NullPointerException - if the specified collection is null
IllegalArgumentException - if the specified collection is this queue, or some property of an element of this queue prevents it from being added to the specified collection

LinkedTransferQueue.drainTo(java.util.Collection, int) (New)

drainTo

public int drainTo(Collection<? super E> c,
                   int maxElements)
Description copied from interface: BlockingQueue
Removes at most the given number of available elements from this queue and adds them to the given collection. A failure encountered while attempting to add elements to collection c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Specified by:
drainTo in interface BlockingQueue<E>
Parameters:
c - the collection to transfer elements into
maxElements - the maximum number of elements to transfer
Returns:
the number of elements transferred
Throws:
NullPointerException - if the specified collection is null
IllegalArgumentException - if the specified collection is this queue, or some property of an element of this queue prevents it from being added to the specified collection

LinkedTransferQueue.getWaitingConsumerCount() (New)

getWaitingConsumerCount

public int getWaitingConsumerCount()
Description copied from interface: TransferQueue
Returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or timed poll. The return value is an approximation of a momentary state of affairs, that may be inaccurate if consumers have completed or given up waiting. The value may be useful for monitoring and heuristics, but not for synchronization control. Implementations of this method are likely to be noticeably slower than those for TransferQueue.hasWaitingConsumer().

Specified by:
getWaitingConsumerCount in interface TransferQueue<E>
Returns:
the number of consumers waiting to receive elements

LinkedTransferQueue.hasWaitingConsumer() (New)

hasWaitingConsumer

public boolean hasWaitingConsumer()
Description copied from interface: TransferQueue
Returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take() or timed poll. The return value represents a momentary state of affairs.

Specified by:
hasWaitingConsumer in interface TransferQueue<E>
Returns:
true if there is at least one waiting consumer

LinkedTransferQueue.isEmpty() (New)

isEmpty

public boolean isEmpty()
Returns true if this queue contains no elements.

Specified by:
isEmpty in interface Collection<E>
Overrides:
isEmpty in class AbstractCollection<E>
Returns:
true if this queue contains no elements

LinkedTransferQueue.iterator() (New)

iterator

public Iterator<E> iterator()
Returns an iterator over the elements in this queue in proper sequence, from head to tail.

The returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

Specified by:
iterator in interface Iterable<E>
Specified by:
iterator in interface Collection<E>
Specified by:
iterator in class AbstractCollection<E>
Returns:
an iterator over the elements in this queue in proper sequence

LinkedTransferQueue.offer(java.lang.Object) (New)

offer

public boolean offer(E e)
Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return false.

Specified by:
offer in interface BlockingQueue<E>
Specified by:
offer in interface Queue<E>
Parameters:
e - the element to add
Returns:
true (as specified by BlockingQueue.offer)
Throws:
NullPointerException - if the specified element is null

LinkedTransferQueue.offer(java.lang.Object,long,java.util.concurrent.TimeUnit) (New)

offer

public boolean offer(E e,
                     long timeout,
                     TimeUnit unit)
Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never block or return false.

Specified by:
offer in interface BlockingQueue<E>
Parameters:
e - the element to add
timeout - how long to wait before giving up, in units of unit
unit - a TimeUnit determining how to interpret the timeout parameter
Returns:
true (as specified by BlockingQueue.offer)
Throws:
NullPointerException - if the specified element is null

LinkedTransferQueue.peek() (New)

peek

public E peek()
Specified by:
peek in interface Queue<E>

LinkedTransferQueue.poll() (New)

poll

public E poll()
Specified by:
poll in interface Queue<E>

LinkedTransferQueue.poll(long, java.util.concurrent.TimeUnit) (New)

poll

public E poll(long timeout,
              TimeUnit unit)
       throws InterruptedException
Description copied from interface: BlockingQueue
Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.

Specified by:
poll in interface BlockingQueue<E>
Parameters:
timeout - how long to wait before giving up, in units of unit
unit - a TimeUnit determining how to interpret the timeout parameter
Returns:
the head of this queue, or null if the specified waiting time elapses before an element is available
Throws:
InterruptedException - if interrupted while waiting

LinkedTransferQueue.put(java.lang.Object) (New)

put

public void put(E e)
Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never block.

Specified by:
put in interface BlockingQueue<E>
Parameters:
e - the element to add
Throws:
NullPointerException - if the specified element is null

LinkedTransferQueue.remainingCapacity() (New)

remainingCapacity

public int remainingCapacity()
Always returns Integer.MAX_VALUE because a LinkedTransferQueue is not capacity constrained.

Specified by:
remainingCapacity in interface BlockingQueue<E>
Returns:
Integer.MAX_VALUE (as specified by BlockingQueue.remainingCapacity())

LinkedTransferQueue.remove(java.lang.Object) (New)

remove

public boolean remove(Object o)
Removes a single instance of the specified element from this queue, if it is present. More formally, removes an element e such that o.equals(e), if this queue contains one or more such elements. Returns true if this queue contained the specified element (or equivalently, if this queue changed as a result of the call).

Specified by:
remove in interface Collection<E>
Specified by:
remove in interface BlockingQueue<E>
Overrides:
remove in class AbstractCollection<E>
Parameters:
o - element to be removed from this queue, if present
Returns:
true if this queue changed as a result of the call

LinkedTransferQueue.size() (New)

size

public int size()
Returns the number of elements in this queue. If this queue contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Beware that, unlike in most collections, this method is NOT a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires an O(n) traversal.

Specified by:
size in interface Collection<E>
Specified by:
size in class AbstractCollection<E>
Returns:
the number of elements in this queue

LinkedTransferQueue.take() (New)

take

public E take()
       throws InterruptedException
Description copied from interface: BlockingQueue
Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Specified by:
take in interface BlockingQueue<E>
Returns:
the head of this queue
Throws:
InterruptedException - if interrupted while waiting

LinkedTransferQueue.transfer(java.lang.Object) (New)

transfer

public void transfer(E e)
              throws InterruptedException
Transfers the element to a consumer, waiting if necessary to do so.

More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in take() or timed poll), else inserts the specified element at the tail of this queue and waits until the element is received by a consumer.

Specified by:
transfer in interface TransferQueue<E>
Parameters:
e - the element to transfer
Throws:
NullPointerException - if the specified element is null
InterruptedException - if interrupted while waiting, in which case the element is not left enqueued

LinkedTransferQueue.tryTransfer(java.lang.Object) (New)

tryTransfer

public boolean tryTransfer(E e)
Transfers the element to a waiting consumer immediately, if possible.

More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in take() or timed poll), otherwise returning false without enqueuing the element.

Specified by:
tryTransfer in interface TransferQueue<E>
Parameters:
e - the element to transfer
Returns:
true if the element was transferred, else false
Throws:
NullPointerException - if the specified element is null

LinkedTransferQueue.tryTransfer(java.lang.Object,long,java.util.concurrent.TimeUnit) (New)

tryTransfer

public boolean tryTransfer(E e,
                           long timeout,
                           TimeUnit unit)
                    throws InterruptedException
Transfers the element to a consumer if it is possible to do so before the timeout elapses.

More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in take() or timed poll), else inserts the specified element at the tail of this queue and waits until the element is received by a consumer, returning false if the specified wait time elapses before the element can be transferred.

Specified by:
tryTransfer in interface TransferQueue<E>
Parameters:
e - the element to transfer
timeout - how long to wait before giving up, in units of unit
unit - a TimeUnit determining how to interpret the timeout parameter
Returns:
true if successful, or false if the specified waiting time elapses before completion, in which case the element is not left enqueued
Throws:
NullPointerException - if the specified element is null
InterruptedException - if interrupted while waiting, in which case the element is not left enqueued

java.util.concurrent.Phaser (New) (22 methods)

CLASS_COMMENT
Phaser()
Phaser(int)
Phaser(java.util.concurrent.Phaser)
Phaser(java.util.concurrent.Phaser, int)
arrive()
arriveAndAwaitAdvance()
arriveAndDeregister()
awaitAdvance(int)
awaitAdvanceInterruptibly(int)
awaitAdvanceInterruptibly(int, long, java.util.concurrent.TimeUnit)
bulkRegister(int)
forceTermination()
getArrivedParties()
getParent()
getPhase()
getRegisteredParties()
getRoot()
getUnarrivedParties()
isTerminated()
onAdvance(int, int)
register()
toString()

Phaser.CLASS_COMMENT (New)

java.util.concurrent
Class Phaser

java.lang.Object
  extended by java.util.concurrent.Phaser

public class Phaser
extends Object

A reusable synchronization barrier, similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage.

Registration. Unlike the case for other barriers, the number of parties registered to synchronize on a phaser may vary over time. Tasks may be registered at any time (using methods register(), bulkRegister(int), or forms of constructors establishing initial numbers of parties), and optionally deregistered upon any arrival (using arriveAndDeregister()). As is the case with most basic synchronization constructs, registration and deregistration affect only internal counts; they do not establish any further internal bookkeeping, so tasks cannot query whether they are registered. (However, you can introduce such bookkeeping by subclassing this class.)

Synchronization. Like a CyclicBarrier, a Phaser may be repeatedly awaited. Method arriveAndAwaitAdvance() has effect analogous to CyclicBarrier.await. Each generation of a Phaser has an associated phase number. The phase number starts at zero, and advances when all parties arrive at the barrier, wrapping around to zero after reaching Integer.MAX_VALUE. The use of phase numbers enables independent control of actions upon arrival at a barrier and upon awaiting others, via two kinds of methods that may be invoked by any registered party:

  • Arrival. Methods arrive() and arriveAndDeregister() record arrival at a barrier. These methods do not block, but return an associated arrival phase number; that is, the phase number of the barrier to which the arrival applied. When the final party for a given phase arrives, an optional barrier action is performed and the phase advances. Barrier actions, performed by the party triggering a phase advance, are arranged by overriding method onAdvance(int, int), which also controls termination. Overriding this method is similar to, but more flexible than, providing a barrier action to a CyclicBarrier.
  • Waiting. Method awaitAdvance(int) requires an argument indicating an arrival phase number, and returns when the barrier advances to (or is already at) a different phase. Unlike similar constructions using CyclicBarrier, method awaitAdvance continues to wait even if the waiting thread is interrupted. Interruptible and timeout versions are also available, but exceptions encountered while tasks wait interruptibly or with timeout do not change the state of the barrier. If necessary, you can perform any associated recovery within handlers of those exceptions, often after invoking forceTermination. Phasers may also be used by tasks executing in a ForkJoinPool, which will ensure sufficient parallelism to execute tasks when others are blocked waiting for a phase to advance.

Termination. A Phaser may enter a termination state in which all synchronization methods immediately return without updating phaser state or waiting for advance, and indicating (via a negative phase value) that execution is complete. Termination is triggered when an invocation of onAdvance returns true. As illustrated below, when phasers control actions with a fixed number of iterations, it is often convenient to override this method to cause termination when the current phase number reaches a threshold. Method forceTermination() is also available to abruptly release waiting threads and allow them to terminate.

Tiering. Phasers may be tiered (i.e., arranged in tree structures) to reduce contention. Phasers with large numbers of parties that would otherwise experience heavy synchronization contention costs may instead be set up so that groups of sub-phasers share a common parent. This may greatly increase throughput even though it incurs greater per-operation overhead.

Monitoring. While synchronization methods may be invoked only by registered parties, the current state of a phaser may be monitored by any caller. At any given moment there are getRegisteredParties() parties in total, of which getArrivedParties() have arrived at the current phase (getPhase()). When the remaining (getUnarrivedParties()) parties arrive, the phase advances. The values returned by these methods may reflect transient states and so are not in general useful for synchronization control. Method toString() returns snapshots of these state queries in a form convenient for informal monitoring.

Sample usages:

A Phaser may be used instead of a CountDownLatch to control a one-shot action serving a variable number of parties. The typical idiom is for the method setting this up to first register, then start the actions, then deregister, as in:

 void runTasks(List<Runnable> tasks) {
   final Phaser phaser = new Phaser(1); // "1" to register self
   // create and start threads
   for (Runnable task : tasks) {
     phaser.register();
     new Thread() {
       public void run() {
         phaser.arriveAndAwaitAdvance(); // await all creation
         task.run();
       }
     }.start();
   }

   // allow threads to start and deregister self
   phaser.arriveAndDeregister();
 }

One way to cause a set of threads to repeatedly perform actions for a given number of iterations is to override onAdvance:

 void startTasks(List<Runnable> tasks, final int iterations) {
   final Phaser phaser = new Phaser() {
     protected boolean onAdvance(int phase, int registeredParties) {
       return phase >= iterations || registeredParties == 0;
     }
   };
   phaser.register();
   for (final Runnable task : tasks) {
     phaser.register();
     new Thread() {
       public void run() {
         do {
           task.run();
           phaser.arriveAndAwaitAdvance();
         } while (!phaser.isTerminated());
       }
     }.start();
   }
   phaser.arriveAndDeregister(); // deregister self, don't wait
 }
If the main task must later await termination, it may re-register and then execute a similar loop:
 // ...
   phaser.register();
   while (!phaser.isTerminated())
     phaser.arriveAndAwaitAdvance();

Related constructions may be used to await particular phase numbers in contexts where you are sure that the phase will never wrap around Integer.MAX_VALUE. For example:

 void awaitPhase(Phaser phaser, int phase) {
   int p = phaser.register(); // assumes caller not already registered
   while (p < phase) {
     if (phaser.isTerminated())
       // ... deal with unexpected termination
     else
       p = phaser.arriveAndAwaitAdvance();
   }
   phaser.arriveAndDeregister();
 }

To create a set of tasks using a tree of phasers, you could use code of the following form, assuming a Task class with a constructor accepting a phaser that it registers for upon construction:

 void build(Task[] actions, int lo, int hi, Phaser ph) {
   if (hi - lo > TASKS_PER_PHASER) {
     for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
       int j = Math.min(i + TASKS_PER_PHASER, hi);
       build(actions, i, j, new Phaser(ph));
     }
   } else {
     for (int i = lo; i < hi; ++i)
       actions[i] = new Task(ph);
       // assumes new Task(ph) performs ph.register()
   }
 }
 // .. initially called, for n tasks via
 build(new Task[n], 0, n, new Phaser());
The best value of TASKS_PER_PHASER depends mainly on expected barrier synchronization rates. A value as low as four may be appropriate for extremely small per-barrier task bodies (thus high rates), or up to hundreds for extremely large ones.

Implementation notes: This implementation restricts the maximum number of parties to 65535. Attempts to register additional parties result in IllegalStateException. However, you can and should create tiered phasers to accommodate arbitrarily large sets of participants.

Since:
1.7

Phaser.Phaser() (New)

Phaser

public Phaser()
Creates a new phaser without any initially registered parties, initial phase number 0, and no parent. Any thread using this phaser will need to first register for it.

Phaser.Phaser(int) (New)

Phaser

public Phaser(int parties)
Creates a new phaser with the given numbers of registered unarrived parties, initial phase number 0, and no parent.

Parameters:
parties - the number of parties required to trip barrier
Throws:
IllegalArgumentException - if parties less than zero or greater than the maximum number of parties supported

Phaser.Phaser(java.util.concurrent.Phaser) (New)

Phaser

public Phaser(Phaser parent)
Creates a new phaser with the given parent, without any initially registered parties. If parent is non-null this phaser is registered with the parent and its initial phase number is the same as that of parent phaser.

Parameters:
parent - the parent phaser

Phaser.Phaser(java.util.concurrent.Phaser, int) (New)

Phaser

public Phaser(Phaser parent,
              int parties)
Creates a new phaser with the given parent and numbers of registered unarrived parties. If parent is non-null, this phaser is registered with the parent and its initial phase number is the same as that of parent phaser.

Parameters:
parent - the parent phaser
parties - the number of parties required to trip barrier
Throws:
IllegalArgumentException - if parties less than zero or greater than the maximum number of parties supported

Phaser.arrive() (New)

arrive

public int arrive()
Arrives at the barrier, but does not wait for others. (You can in turn wait for others via awaitAdvance(int)). It is an unenforced usage error for an unregistered party to invoke this method.

Returns:
the arrival phase number, or a negative value if terminated
Throws:
IllegalStateException - if not terminated and the number of unarrived parties would become negative

Phaser.arriveAndAwaitAdvance() (New)

arriveAndAwaitAdvance

public int arriveAndAwaitAdvance()
Arrives at the barrier and awaits others. Equivalent in effect to awaitAdvance(arrive()). If you need to await with interruption or timeout, you can arrange this with an analogous construction using one of the other forms of the awaitAdvance method. If instead you need to deregister upon arrival use arriveAndDeregister. It is an unenforced usage error for an unregistered party to invoke this method.

Returns:
the arrival phase number, or a negative number if terminated
Throws:
IllegalStateException - if not terminated and the number of unarrived parties would become negative

Phaser.arriveAndDeregister() (New)

arriveAndDeregister

public int arriveAndDeregister()
Arrives at the barrier and deregisters from it without waiting for others. Deregistration reduces the number of parties required to trip the barrier in future phases. If this phaser has a parent, and deregistration causes this phaser to have zero parties, this phaser also arrives at and is deregistered from its parent. It is an unenforced usage error for an unregistered party to invoke this method.

Returns:
the arrival phase number, or a negative value if terminated
Throws:
IllegalStateException - if not terminated and the number of registered or unarrived parties would become negative

Phaser.awaitAdvance(int) (New)

awaitAdvance

public int awaitAdvance(int phase)
Awaits the phase of the barrier to advance from the given phase value, returning immediately if the current phase of the barrier is not equal to the given phase value or this barrier is terminated. It is an unenforced usage error for an unregistered party to invoke this method.

Parameters:
phase - an arrival phase number, or negative value if terminated; this argument is normally the value returned by a previous call to arrive or its variants
Returns:
the next arrival phase number, or a negative value if terminated or argument is negative

Phaser.awaitAdvanceInterruptibly(int) (New)

awaitAdvanceInterruptibly

public int awaitAdvanceInterruptibly(int phase)
                              throws InterruptedException
Awaits the phase of the barrier to advance from the given phase value, throwing InterruptedException if interrupted while waiting, or returning immediately if the current phase of the barrier is not equal to the given phase value or this barrier is terminated. It is an unenforced usage error for an unregistered party to invoke this method.

Parameters:
phase - an arrival phase number, or negative value if terminated; this argument is normally the value returned by a previous call to arrive or its variants
Returns:
the next arrival phase number, or a negative value if terminated or argument is negative
Throws:
InterruptedException - if thread interrupted while waiting

Phaser.awaitAdvanceInterruptibly(int, long, java.util.concurrent.TimeUnit) (New)

awaitAdvanceInterruptibly

public int awaitAdvanceInterruptibly(int phase,
                                     long timeout,
                                     TimeUnit unit)
                              throws InterruptedException,
                                     TimeoutException
Awaits the phase of the barrier to advance from the given phase value or the given timeout to elapse, throwing InterruptedException if interrupted while waiting, or returning immediately if the current phase of the barrier is not equal to the given phase value or this barrier is terminated. It is an unenforced usage error for an unregistered party to invoke this method.

Parameters:
phase - an arrival phase number, or negative value if terminated; this argument is normally the value returned by a previous call to arrive or its variants
timeout - how long to wait before giving up, in units of unit
unit - a TimeUnit determining how to interpret the timeout parameter
Returns:
the next arrival phase number, or a negative value if terminated or argument is negative
Throws:
InterruptedException - if thread interrupted while waiting
TimeoutException - if timed out while waiting

Phaser.bulkRegister(int) (New)

bulkRegister

public int bulkRegister(int parties)
Adds the given number of new unarrived parties to this phaser.

Parameters:
parties - the number of parties required to trip barrier
Returns:
the arrival phase number to which this registration applied
Throws:
IllegalStateException - if attempting to register more than the maximum supported number of parties

Phaser.forceTermination() (New)

forceTermination

public void forceTermination()
Forces this barrier to enter termination state. Counts of arrived and registered parties are unaffected. If this phaser has a parent, it too is terminated. This method may be useful for coordinating recovery after one or more tasks encounter unexpected exceptions.

Phaser.getArrivedParties() (New)

getArrivedParties

public int getArrivedParties()
Returns the number of registered parties that have arrived at the current phase of this barrier.

Returns:
the number of arrived parties

Phaser.getParent() (New)

getParent

public Phaser getParent()
Returns the parent of this phaser, or null if none.

Returns:
the parent of this phaser, or null if none

Phaser.getPhase() (New)

getPhase

public final int getPhase()
Returns the current phase number. The maximum phase number is Integer.MAX_VALUE, after which it restarts at zero. Upon termination, the phase number is negative.

Returns:
the phase number, or a negative value if terminated

Phaser.getRegisteredParties() (New)

getRegisteredParties

public int getRegisteredParties()
Returns the number of parties registered at this barrier.

Returns:
the number of parties

Phaser.getRoot() (New)

getRoot

public Phaser getRoot()
Returns the root ancestor of this phaser, which is the same as this phaser if it has no parent.

Returns:
the root ancestor of this phaser

Phaser.getUnarrivedParties() (New)

getUnarrivedParties

public int getUnarrivedParties()
Returns the number of registered parties that have not yet arrived at the current phase of this barrier.

Returns:
the number of unarrived parties

Phaser.isTerminated() (New)

isTerminated

public boolean isTerminated()
Returns true if this barrier has been terminated.

Returns:
true if this barrier has been terminated

Phaser.onAdvance(int, int) (New)

onAdvance

protected boolean onAdvance(int phase,
                            int registeredParties)
Overridable method to perform an action upon impending phase advance, and to control termination. This method is invoked upon arrival of the party tripping the barrier (when all other waiting parties are dormant). If this method returns true, then, rather than advance the phase number, this barrier will be set to a final termination state, and subsequent calls to isTerminated() will return true. Any (unchecked) Exception or Error thrown by an invocation of this method is propagated to the party attempting to trip the barrier, in which case no advance occurs.

The arguments to this method provide the state of the phaser prevailing for the current transition. (When called from within an implementation of onAdvance the values returned by methods such as getPhase may or may not reliably indicate the state to which this transition applies.)

The default version returns true when the number of registered parties is zero. Normally, overrides that arrange termination for other reasons should also preserve this property.

You may override this method to perform an action with side effects visible to participating tasks, but it is only sensible to do so in designs where all parties register before any arrive, and all awaitAdvance(int) at each phase. Otherwise, you cannot ensure lack of interference from other parties during the invocation of this method. Additionally, method onAdvance may be invoked more than once per transition if registrations are intermixed with arrivals.

Parameters:
phase - the phase number on entering the barrier
registeredParties - the current number of registered parties
Returns:
true if this barrier should terminate

Phaser.register() (New)

register

public int register()
Adds a new unarrived party to this phaser.

Returns:
the arrival phase number to which this registration applied
Throws:
IllegalStateException - if attempting to register more than the maximum supported number of parties

Phaser.toString() (New)

toString

public String toString()
Returns a string identifying this phaser, as well as its state. The state, in brackets, includes the String "phase = " followed by the phase number, "parties = " followed by the number of registered parties, and "arrived = " followed by the number of arrived parties.

Overrides:
toString in class Object
Returns:
a string identifying this barrier, as well as its state

java.util.concurrent.RecursiveAction (New) (5 methods)

CLASS_COMMENT
RecursiveAction()
compute()
exec()
getRawResult()
setRawResult(java.lang.Void)

RecursiveAction.CLASS_COMMENT (New)

java.util.concurrent
Class RecursiveAction

java.lang.Object
  extended by java.util.concurrent.ForkJoinTask<Void>
      extended by java.util.concurrent.RecursiveAction
All Implemented Interfaces:
Serializable, Future<Void>

public abstract class RecursiveAction
extends ForkJoinTask<Void>

A recursive resultless ForkJoinTask. This class establishes conventions to parameterize resultless actions as Void ForkJoinTasks. Because null is the only valid value of type Void, methods such as join always return null upon completion.

Sample Usages. Here is a sketch of a ForkJoin sort that sorts a given long[] array:

 class SortTask extends RecursiveAction {
   final long[] array; final int lo; final int hi;
   SortTask(long[] array, int lo, int hi) {
     this.array = array; this.lo = lo; this.hi = hi;
   }
   protected void compute() {
     if (hi - lo < THRESHOLD)
       sequentiallySort(array, lo, hi);
     else {
       int mid = (lo + hi) >>> 1;
       invokeAll(new SortTask(array, lo, mid),
                 new SortTask(array, mid, hi));
       merge(array, lo, hi);
     }
   }
 }
You could then sort anArray by creating new SortTask(anArray, 0, anArray.length-1) and invoking it in a ForkJoinPool. As a more concrete simple example, the following task increments each element of an array:
 class IncrementTask extends RecursiveAction {
   final long[] array; final int lo; final int hi;
   IncrementTask(long[] array, int lo, int hi) {
     this.array = array; this.lo = lo; this.hi = hi;
   }
   protected void compute() {
     if (hi - lo < THRESHOLD) {
       for (int i = lo; i < hi; ++i)
         array[i]++;
     }
     else {
       int mid = (lo + hi) >>> 1;
       invokeAll(new IncrementTask(array, lo, mid),
                 new IncrementTask(array, mid, hi));
     }
   }
 }

The following example illustrates some refinements and idioms that may lead to better performance: RecursiveActions need not be fully recursive, so long as they maintain the basic divide-and-conquer approach. Here is a class that sums the squares of each element of a double array, by subdividing out only the right-hand-sides of repeated divisions by two, and keeping track of them with a chain of next references. It uses a dynamic threshold based on method getSurplusQueuedTaskCount, but counterbalances potential excess partitioning by directly performing leaf actions on unstolen tasks rather than further subdividing.

 double sumOfSquares(ForkJoinPool pool, double[] array) {
   int n = array.length;
   int seqSize = 1 + n / (8 * pool.getParallelism());
   Applyer a = new Applyer(array, 0, n, seqSize, null);
   pool.invoke(a);
   return a.result;
 }

 class Applyer extends RecursiveAction {
   final double[] array;
   final int lo, hi, seqSize;
   double result;
   Applyer next; // keeps track of right-hand-side tasks
   Applyer(double[] array, int lo, int hi, int seqSize, Applyer next) {
     this.array = array; this.lo = lo; this.hi = hi;
     this.seqSize = seqSize; this.next = next;
   }

   double atLeaf(int l, int r) {
     double sum = 0;
     for (int i = l; i < h; ++i) // perform leftmost base step
       sum += array[i] * array[i];
     return sum;
   }

   protected void compute() {
     int l = lo;
     int h = hi;
     Applyer right = null;
     while (h - l > 1 && getSurplusQueuedTaskCount() <= 3) {
        int mid = (l + h) >>> 1;
        right = new Applyer(array, mid, h, seqSize, right);
        right.fork();
        h = mid;
     }
     double sum = atLeaf(l, h);
     while (right != null) {
        if (right.tryUnfork()) // directly calculate if not stolen
          sum += right.atLeaf(right.lo, right.hi);
       else {
          right.helpJoin();
          sum += right.result;
        }
        right = right.next;
      }
     result = sum;
   }
 }

Since:
1.7
See Also:
Serialized Form

RecursiveAction.RecursiveAction() (New)

RecursiveAction

public RecursiveAction()

RecursiveAction.compute() (New)

compute

protected abstract void compute()
The main computation performed by this task.

RecursiveAction.exec() (New)

exec

protected final boolean exec()
Implements execution conventions for RecursiveActions.

Specified by:
exec in class ForkJoinTask<Void>
Returns:
true if completed normally

RecursiveAction.getRawResult() (New)

getRawResult

public final Void getRawResult()
Always returns null.

Specified by:
getRawResult in class ForkJoinTask<Void>
Returns:
the result, or null if not completed

RecursiveAction.setRawResult(java.lang.Void) (New)

setRawResult

protected final void setRawResult(Void mustBeNull)
Requires null completion value.

Specified by:
setRawResult in class ForkJoinTask<Void>
Parameters:
mustBeNull - the value

java.util.concurrent.RecursiveTask (New) (5 methods)

CLASS_COMMENT
RecursiveTask()
compute()
exec()
getRawResult()
setRawResult(java.lang.Object)

RecursiveTask.CLASS_COMMENT (New)

java.util.concurrent
Class RecursiveTask<V>

java.lang.Object
  extended by java.util.concurrent.ForkJoinTask<V>
      extended by java.util.concurrent.RecursiveTask<V>
All Implemented Interfaces:
Serializable, Future<V>

public abstract class RecursiveTask<V>
extends ForkJoinTask<V>

A recursive result-bearing ForkJoinTask.

For a classic example, here is a task computing Fibonacci numbers:

 class Fibonacci extends RecursiveTask<Integer> {
   final int n;
   Fibonacci(int n) { this.n = n; }
   Integer compute() {
     if (n <= 1)
        return n;
     Fibonacci f1 = new Fibonacci(n - 1);
     f1.fork();
     Fibonacci f2 = new Fibonacci(n - 2);
     return f2.compute() + f1.join();
   }
 }
However, besides being a dumb way to compute Fibonacci functions (there is a simple fast linear algorithm that you'd use in practice), this is likely to perform poorly because the smallest subtasks are too small to be worthwhile splitting up. Instead, as is the case for nearly all fork/join applications, you'd pick some minimum granularity size (for example 10 here) for which you always sequentially solve rather than subdividing.

Since:
1.7
See Also:
Serialized Form

RecursiveTask.RecursiveTask() (New)

RecursiveTask

public RecursiveTask()

RecursiveTask.compute() (New)

compute

protected abstract V compute()
The main computation performed by this task.

RecursiveTask.exec() (New)

exec

protected final boolean exec()
Implements execution conventions for RecursiveTask.

Specified by:
exec in class ForkJoinTask<V>
Returns:
true if completed normally

RecursiveTask.getRawResult() (New)

getRawResult

public final V getRawResult()
Description copied from class: ForkJoinTask
Returns the result that would be returned by ForkJoinTask.join(), even if this task completed abnormally, or null if this task is not known to have been completed. This method is designed to aid debugging, as well as to support extensions. Its use in any other context is discouraged.

Specified by:
getRawResult in class ForkJoinTask<V>
Returns:
the result, or null if not completed

RecursiveTask.setRawResult(java.lang.Object) (New)

setRawResult

protected final void setRawResult(V value)
Description copied from class: ForkJoinTask
Forces the given value to be returned as a result. This method is designed to support extensions, and should not in general be called otherwise.

Specified by:
setRawResult in class ForkJoinTask<V>
Parameters:
value - the value

java.util.concurrent.ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor.CLASS_COMMENT

java.util.concurrent
Class ScheduledThreadPoolExecutor


 java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
      extended by java.util.concurrent.ThreadPoolExecutor
          extended by java.util.concurrent.ScheduledThreadPoolExecutor
 
All Implemented Interfaces:
Executor , ExecutorService , ScheduledExecutorService

public class ScheduledThreadPoolExecutor
 extends ThreadPoolExecutor
 implements ScheduledExecutorService

A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.

Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission.

When a submitted task is cancelled before it is run, execution is suppressed. By default, such a cancelled task is not automatically removed from the work queue until its delay elapses. While this enables further inspection and monitoring, it may also cause unbounded retention of cancelled tasks. To avoid this, set setRemoveOnCancelPolicy(boolean) to true , which causes tasks to be immediately removed from the work queue at time of cancellation.

Successive executions of a task scheduled via scheduleAtFixedRate or scheduleWithFixedDelay do not overlap. While different executions may be performed by different threads, the effects of prior executions happen-before those of subsequent ones.

While this class inherits from ThreadPoolExecutor , a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. Additionally, it is almost never a good idea to set corePoolSize to zero or use allowCoreThreadTimeOut because this may leave the pool without threads to handle tasks once they become eligible to run.

Extension notes: This class overrides the execute and submit methods to generate internal ScheduledFuture objects to control per-task delays and scheduling. To preserve functionality, any further overrides of these methods in subclasses must invoke superclass versions, which effectively disables additional task customization. However, this class provides alternative protected extension method decorateTask (one version each for Runnable and Callable ) that can be used to customize the concrete task types used to execute commands entered via execute , submit , schedule , scheduleAtFixedRate , and scheduleWithFixedDelay . By default, a ScheduledThreadPoolExecutor uses a task type extending FutureTask . However, this may be modified or replaced using subclasses of the form:

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {
 
   static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }
 
   protected <V> RunnableScheduledFuture<V> decorateTask(
                Runnable r, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(r, task);
   }
 
   protected <V> RunnableScheduledFuture<V> decorateTask(
                Callable<V> c, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(c, task);
   }
   // ... add constructors, etc.
 }

Since:
1.5

java.util.concurrent
Class ScheduledThreadPoolExecutor

java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
      extended by java.util.concurrent.ThreadPoolExecutor
          extended by java.util.concurrent.ScheduledThreadPoolExecutor
All Implemented Interfaces:
Executor, ExecutorService, ScheduledExecutorService

public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService

A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.

Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission.

When a submitted task is cancelled before it is run, execution is suppressed. By default, such a cancelled task is not automatically removed from the work queue until its delay elapses. While this enables further inspection and monitoring, it may also cause unbounded retention of cancelled tasks. To avoid this, set setRemoveOnCancelPolicy(boolean) to true, which causes tasks to be immediately removed from the work queue at time of cancellation.

While this class inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. Additionally, it is almost never a good idea to set corePoolSize to zero or use allowCoreThreadTimeOut because this may leave the pool without threads to handle tasks once they become eligible to run.

Extension notes: This class overrides the execute and submit methods to generate internal ScheduledFuture objects to control per-task delays and scheduling. To preserve functionality, any further overrides of these methods in subclasses must invoke superclass versions, which effectively disables additional task customization. However, this class provides alternative protected extension method decorateTask (one version each for Runnable and Callable) that can be used to customize the concrete task types used to execute commands entered via execute, submit, schedule, scheduleAtFixedRate, and scheduleWithFixedDelay. By default, a ScheduledThreadPoolExecutor uses a task type extending FutureTask. However, this may be modified or replaced using subclasses of the form:

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {

   static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Runnable r, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(r, task);
   }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Callable<V> c, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(c, task);
   }
   // ... add constructors, etc.
 }

Since:
1.5

java.util.concurrent
Class ScheduledThreadPoolExecutor

java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
      extended by java.util.concurrent.ThreadPoolExecutor
          extended by java.util.concurrent.ScheduledThreadPoolExecutor
All Implemented Interfaces:
Executor, ExecutorService, ScheduledExecutorService

public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService

A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.

Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission.

When a submitted task is cancelled before it is run, execution is suppressed. By default, such a cancelled task is not automatically removed from the work queue until its delay elapses. While this enables further inspection and monitoring, it may also cause unbounded retention of cancelled tasks. To avoid this, set setRemoveOnCancelPolicy(boolean) to true, which causes tasks to be immediately removed from the work queue at time of cancellation.

Successive executions of a task scheduled via scheduleAtFixedRate or scheduleWithFixedDelay do not overlap. While different executions may be performed by different threads, the effects of prior executions happen-before those of subsequent ones.

While this class inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. Additionally, it is almost never a good idea to set corePoolSize to zero or use allowCoreThreadTimeOut because this may leave the pool without threads to handle tasks once they become eligible to run.

Extension notes: This class overrides the execute and submit methods to generate internal ScheduledFuture objects to control per-task delays and scheduling. To preserve functionality, any further overrides of these methods in subclasses must invoke superclass versions, which effectively disables additional task customization. However, this class provides alternative protected extension method decorateTask (one version each for Runnable and Callable) that can be used to customize the concrete task types used to execute commands entered via execute, submit, schedule, scheduleAtFixedRate, and scheduleWithFixedDelay. By default, a ScheduledThreadPoolExecutor uses a task type extending FutureTask. However, this may be modified or replaced using subclasses of the form:

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {

   static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Runnable r, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(r, task);
   }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Callable<V> c, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(c, task);
   }
   // ... add constructors, etc.
 }

Since:
1.5

java.util.concurrent.ThreadLocalRandom (New) (8 methods)

CLASS_COMMENT
current()
next(int)
nextDouble(double)
nextDouble(double, double)
nextInt(int, int)
nextLong(long)
nextLong(long, long)
setSeed(long)

ThreadLocalRandom.CLASS_COMMENT (New)

java.util.concurrent
Class ThreadLocalRandom

java.lang.Object
  extended by java.util.Random
      extended by java.util.concurrent.ThreadLocalRandom
All Implemented Interfaces:
Serializable

public class ThreadLocalRandom
extends Random

A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.

Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.

This class also provides additional commonly used bounded random generation methods.

Since:
1.7
See Also:
Serialized Form

ThreadLocalRandom.current() (New)

current

public static ThreadLocalRandom current()
Returns the current thread's ThreadLocalRandom.

Returns:
the current thread's ThreadLocalRandom

ThreadLocalRandom.next(int) (New)

next

protected int next(int bits)
Description copied from class: Random
Generates the next pseudorandom number. Subclasses should override this, as this is used by all other methods.

The general contract of next is that it returns an int value and if the argument bits is between 1 and 32 (inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be 0 or 1. The method next is implemented by class Random by atomically updating the seed to

(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
and returning
(int)(seed >>> (48 - bits)).
This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.2.1.

Overrides:
next in class Random
Parameters:
bits - random bits
Returns:
the next pseudorandom value from this random number generator's sequence

ThreadLocalRandom.nextDouble(double) (New)

nextDouble

public double nextDouble(double n)
Returns a pseudorandom, uniformly distributed double value between 0 (inclusive) and the specified value (exclusive).

Parameters:
n - the bound on the random number to be returned. Must be positive.
Returns:
the next value
Throws:
IllegalArgumentException - if n is not positive

ThreadLocalRandom.nextDouble(double, double) (New)

nextDouble

public double nextDouble(double least,
                         double bound)
Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).

Parameters:
least - the least value returned
bound - the upper bound (exclusive)
Returns:
the next value
Throws:
IllegalArgumentException - if least greater than or equal to bound

ThreadLocalRandom.nextInt(int, int) (New)

nextInt

public int nextInt(int least,
                   int bound)
Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).

Parameters:
least - the least value returned
bound - the upper bound (exclusive)
Returns:
the next value
Throws:
IllegalArgumentException - if least greater than or equal to bound

ThreadLocalRandom.nextLong(long) (New)

nextLong

public long nextLong(long n)
Returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive).

Parameters:
n - the bound on the random number to be returned. Must be positive.
Returns:
the next value
Throws:
IllegalArgumentException - if n is not positive

ThreadLocalRandom.nextLong(long, long) (New)

nextLong

public long nextLong(long least,
                     long bound)
Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).

Parameters:
least - the least value returned
bound - the upper bound (exclusive)
Returns:
the next value
Throws:
IllegalArgumentException - if least greater than or equal to bound

ThreadLocalRandom.setSeed(long) (New)

setSeed

public void setSeed(long seed)
Throws UnsupportedOperationException. Setting seeds in this generator is not supported.

Overrides:
setSeed in class Random
Parameters:
seed - the initial seed
Throws:
UnsupportedOperationException - always

java.util.concurrent.TransferQueue (New) (5 methods)

CLASS_COMMENT
getWaitingConsumerCount()
hasWaitingConsumer()
transfer(java.lang.Object)
tryTransfer(java.lang.Object)
tryTransfer(java.lang.Object,long,java.util.concurrent.TimeUnit)

TransferQueue.CLASS_COMMENT (New)

java.util.concurrent
Interface TransferQueue<E>

Type Parameters:
E - the type of elements held in this collection
All Superinterfaces:
BlockingQueue<E>, Collection<E>, Iterable<E>, Queue<E>
All Known Implementing Classes:
LinkedTransferQueue

public interface TransferQueue<E>
extends BlockingQueue<E>

A BlockingQueue in which producers may wait for consumers to receive elements. A TransferQueue may be useful for example in message passing applications in which producers sometimes (using method transfer(E)) await receipt of elements by consumers invoking take or poll, while at other times enqueue elements (via method put) without waiting for receipt. Non-blocking and time-out versions of tryTransfer are also available. A TransferQueue may also be queried, via hasWaitingConsumer(), whether there are any threads waiting for items, which is a converse analogy to a peek operation.

Like other blocking queues, a TransferQueue may be capacity bounded. If so, an attempted transfer operation may initially block waiting for available space, and/or subsequently block waiting for reception by a consumer. Note that in a queue with zero capacity, such as SynchronousQueue, put and transfer are effectively synonymous.

This interface is a member of the Java Collections Framework.

Since:
1.7

TransferQueue.getWaitingConsumerCount() (New)

getWaitingConsumerCount

int getWaitingConsumerCount()
Returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or timed poll. The return value is an approximation of a momentary state of affairs, that may be inaccurate if consumers have completed or given up waiting. The value may be useful for monitoring and heuristics, but not for synchronization control. Implementations of this method are likely to be noticeably slower than those for hasWaitingConsumer().

Returns:
the number of consumers waiting to receive elements

TransferQueue.hasWaitingConsumer() (New)

hasWaitingConsumer

boolean hasWaitingConsumer()
Returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take() or timed poll. The return value represents a momentary state of affairs.

Returns:
true if there is at least one waiting consumer

TransferQueue.transfer(java.lang.Object) (New)

transfer

void transfer(E e)
              throws InterruptedException
Transfers the element to a consumer, waiting if necessary to do so.

More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in BlockingQueue.take() or timed poll), else waits until the element is received by a consumer.

Parameters:
e - the element to transfer
Throws:
InterruptedException - if interrupted while waiting, in which case the element is not left enqueued
ClassCastException - if the class of the specified element prevents it from being added to this queue
NullPointerException - if the specified element is null
IllegalArgumentException - if some property of the specified element prevents it from being added to this queue

TransferQueue.tryTransfer(java.lang.Object) (New)

tryTransfer

boolean tryTransfer(E e)
Transfers the element to a waiting consumer immediately, if possible.

More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in BlockingQueue.take() or timed poll), otherwise returning false without enqueuing the element.

Parameters:
e - the element to transfer
Returns:
true if the element was transferred, else false
Throws:
ClassCastException - if the class of the specified element prevents it from being added to this queue
NullPointerException - if the specified element is null
IllegalArgumentException - if some property of the specified element prevents it from being added to this queue

TransferQueue.tryTransfer(java.lang.Object,long,java.util.concurrent.TimeUnit) (New)

tryTransfer

boolean tryTransfer(E e,
                    long timeout,
                    TimeUnit unit)
                    throws InterruptedException
Transfers the element to a consumer if it is possible to do so before the timeout elapses.

More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in BlockingQueue.take() or timed poll), else waits until the element is received by a consumer, returning false if the specified wait time elapses before the element can be transferred.

Parameters:
e - the element to transfer
timeout - how long to wait before giving up, in units of unit
unit - a TimeUnit determining how to interpret the timeout parameter
Returns:
true if successful, or false if the specified waiting time elapses before completion, in which case the element is not left enqueued
Throws:
InterruptedException - if interrupted while waiting, in which case the element is not left enqueued
ClassCastException - if the class of the specified element prevents it from being added to this queue
NullPointerException - if the specified element is null
IllegalArgumentException - if some property of the specified element prevents it from being added to this queue

java.util.concurrent.package-summary

package-summary.PACKAGE_DESCRIPTION

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 java.util.concurrent.locks and java.util.concurrent.atomic packages.

Executors

Interfaces. 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. ExecutorService provides a more complete asynchronous task execution framework. An ExecutorService manages queuing and scheduling of tasks, and allows controlled shutdown. The ScheduledExecutorService subinterface and associated interfaces add support for delayed and periodic task execution. ExecutorServices provide methods arranging asynchronous execution of any function expressed as Callable , the result-bearing analog of Runnable . A Future returns the results of a function, allows determination of whether execution has completed, and provides a means to cancel execution. A RunnableFuture is a Future that possesses a run method that upon execution, sets its results.

Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor provide tunable, flexible thread pools. 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. Other utilities based on Executors include the concrete class FutureTask providing a common extensible implementation of Futures, and ExecutorCompletionService , that assists in coordinating the processing of groups of asynchronous tasks.

Class ForkJoinPool provides an Executor primarily designed for processing instances of ForkJoinTask and its subclasses. These classes employ a work-stealing scheduler that attains high throughput for tasks conforming to restrictions that often hold in computation-intensive parallel processing.

Queues

The 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.

Extended interface TransferQueue , and implementation LinkedTransferQueue introduce a synchronous transfer method (along with related features) in which a producer may optionally block awaiting its consumer.

The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provides an implementation.

Timing

The TimeUnit class provides multiple granularities (including nanoseconds) for specifying and controlling time-out based operations. Most 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. Implementations make a "best effort" to detect time-outs as soon as possible after they occur. However, an indefinite amount of time may elapse between a time-out being detected and a thread actually executing again after that time-out. All methods that accept timeout parameters treat values less than or equal to zero to mean not to wait at all. To wait "forever", you can use a value of Long.MAX_VALUE .

Synchronizers

Five Four classes aid common special-purpose synchronization idioms.
  • Semaphore is a classic concurrency tool.
  • CountDownLatch is a very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
  • A CyclicBarrier is a resettable multiway synchronization point useful in some styles of parallel programming.
  • A Phaser provides a more flexible form of barrier that may be used to control phased computation among multiple threads.
  • An Exchanger allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.

Concurrent Collections

Besides Queues, this package supplies Collection implementations designed for use in multithreaded contexts: ConcurrentHashMap , ConcurrentSkipListMap , ConcurrentSkipListSet , CopyOnWriteArrayList , and CopyOnWriteArraySet . When many threads are expected to access a given collection, a ConcurrentHashMap is normally preferable to a synchronized HashMap , and a ConcurrentSkipListMap is normally preferable to a synchronized TreeMap . A CopyOnWriteArrayList is preferable to a synchronized ArrayList when the expected number of reads and traversals greatly outnumber the number of updates to a list.

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. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability. In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.

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.

Memory Consistency Properties

Chapter 17 of the Java Language Specification defines the happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation. The synchronized and volatile constructs, as well as the Thread.start() and Thread.join() methods, can form happens-before relationships. In particular:
  • Each action in a thread happens-before every action in that thread that comes later in the program's order.
  • An unlock ( synchronized block or method exit) of a monitor happens-before every subsequent lock ( synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.
  • A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.
  • A call to start on a thread happens-before any action in the started thread.
  • All actions in a thread happen-before any other thread successfully returns from a join on that thread.
The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:
  • Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
  • Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService .
  • Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
  • Actions prior to "releasing" synchronizer methods such as Lock.unlock , Semaphore.release , and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock , Semaphore.acquire , Condition.await , and CountDownLatch.await on the same synchronizer object in another thread.
  • For each pair of threads that successfully exchange objects via an Exchanger , actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
  • Actions prior to calling CyclicBarrier.await and Phaser.awaitAdvance (as well as its variants) happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.

Since:
1.5

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 java.util.concurrent.locks and java.util.concurrent.atomic packages.

Executors

Interfaces. 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. ExecutorService provides a more complete asynchronous task execution framework. An ExecutorService manages queuing and scheduling of tasks, and allows controlled shutdown. The ScheduledExecutorService subinterface and associated interfaces add support for delayed and periodic task execution. ExecutorServices provide methods arranging asynchronous execution of any function expressed as Callable, the result-bearing analog of Runnable. A Future returns the results of a function, allows determination of whether execution has completed, and provides a means to cancel execution. A RunnableFuture is a Future that possesses a run method that upon execution, sets its results.

Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor provide tunable, flexible thread pools. 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. Other utilities based on Executors include the concrete class FutureTask providing a common extensible implementation of Futures, and ExecutorCompletionService, that assists in coordinating the processing of groups of asynchronous tasks.

Queues

The 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.

The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provides an implementation.

Timing

The TimeUnit class provides multiple granularities (including nanoseconds) for specifying and controlling time-out based operations. Most 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. Implementations make a "best effort" to detect time-outs as soon as possible after they occur. However, an indefinite amount of time may elapse between a time-out being detected and a thread actually executing again after that time-out. All methods that accept timeout parameters treat values less than or equal to zero to mean not to wait at all. To wait "forever", you can use a value of Long.MAX_VALUE.

Synchronizers

Four classes aid common special-purpose synchronization idioms. Semaphore is a classic concurrency tool. CountDownLatch is a very simple yet very common utility for blocking until a given number of signals, events, or conditions hold. A CyclicBarrier is a resettable multiway synchronization point useful in some styles of parallel programming. An Exchanger allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.

Concurrent Collections

Besides Queues, this package supplies Collection implementations designed for use in multithreaded contexts: ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentSkipListSet, CopyOnWriteArrayList, and CopyOnWriteArraySet. When many threads are expected to access a given collection, a ConcurrentHashMap is normally preferable to a synchronized HashMap, and a ConcurrentSkipListMap is normally preferable to a synchronized TreeMap. A CopyOnWriteArrayList is preferable to a synchronized ArrayList when the expected number of reads and traversals greatly outnumber the number of updates to a list.

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. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability. In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.

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.

Memory Consistency Properties

Chapter 17 of the Java Language Specification defines the happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation. The synchronized and volatile constructs, as well as the Thread.start() and Thread.join() methods, can form happens-before relationships. In particular:
  • Each action in a thread happens-before every action in that thread that comes later in the program's order.
  • An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.
  • A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.
  • A call to start on a thread happens-before any action in the started thread.
  • All actions in a thread happen-before any other thread successfully returns from a join on that thread.
The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:
  • Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
  • Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.
  • Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
  • Actions prior to "releasing" synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.
  • For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
  • Actions prior to calling CyclicBarrier.await happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.

Since:
1.5

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 java.util.concurrent.locks and java.util.concurrent.atomic packages.

Executors

Interfaces. 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. ExecutorService provides a more complete asynchronous task execution framework. An ExecutorService manages queuing and scheduling of tasks, and allows controlled shutdown. The ScheduledExecutorService subinterface and associated interfaces add support for delayed and periodic task execution. ExecutorServices provide methods arranging asynchronous execution of any function expressed as Callable, the result-bearing analog of Runnable. A Future returns the results of a function, allows determination of whether execution has completed, and provides a means to cancel execution. A RunnableFuture is a Future that possesses a run method that upon execution, sets its results.

Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor provide tunable, flexible thread pools. 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. Other utilities based on Executors include the concrete class FutureTask providing a common extensible implementation of Futures, and ExecutorCompletionService, that assists in coordinating the processing of groups of asynchronous tasks.

Class ForkJoinPool provides an Executor primarily designed for processing instances of ForkJoinTask and its subclasses. These classes employ a work-stealing scheduler that attains high throughput for tasks conforming to restrictions that often hold in computation-intensive parallel processing.

Queues

The 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.

Extended interface TransferQueue, and implementation LinkedTransferQueue introduce a synchronous transfer method (along with related features) in which a producer may optionally block awaiting its consumer.

The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provides an implementation.

Timing

The TimeUnit class provides multiple granularities (including nanoseconds) for specifying and controlling time-out based operations. Most 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. Implementations make a "best effort" to detect time-outs as soon as possible after they occur. However, an indefinite amount of time may elapse between a time-out being detected and a thread actually executing again after that time-out. All methods that accept timeout parameters treat values less than or equal to zero to mean not to wait at all. To wait "forever", you can use a value of Long.MAX_VALUE.

Synchronizers

Five classes aid common special-purpose synchronization idioms.
  • Semaphore is a classic concurrency tool.
  • CountDownLatch is a very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
  • A CyclicBarrier is a resettable multiway synchronization point useful in some styles of parallel programming.
  • A Phaser provides a more flexible form of barrier that may be used to control phased computation among multiple threads.
  • An Exchanger allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.

Concurrent Collections

Besides Queues, this package supplies Collection implementations designed for use in multithreaded contexts: ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentSkipListSet, CopyOnWriteArrayList, and CopyOnWriteArraySet. When many threads are expected to access a given collection, a ConcurrentHashMap is normally preferable to a synchronized HashMap, and a ConcurrentSkipListMap is normally preferable to a synchronized TreeMap. A CopyOnWriteArrayList is preferable to a synchronized ArrayList when the expected number of reads and traversals greatly outnumber the number of updates to a list.

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. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability. In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.

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.

Memory Consistency Properties

Chapter 17 of the Java Language Specification defines the happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation. The synchronized and volatile constructs, as well as the Thread.start() and Thread.join() methods, can form happens-before relationships. In particular:
  • Each action in a thread happens-before every action in that thread that comes later in the program's order.
  • An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.
  • A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.
  • A call to start on a thread happens-before any action in the started thread.
  • All actions in a thread happen-before any other thread successfully returns from a join on that thread.
The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:
  • Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
  • Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.
  • Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
  • Actions prior to "releasing" synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.
  • For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
  • Actions prior to calling CyclicBarrier.await and Phaser.awaitAdvance (as well as its variants) happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.

Since:
1.5