Prefer modern libraries for concurrency

Version 1.5 of the JDK included a new package called java.util.concurrent. It contains modern tools for operations involving threads. You should usually prefer using this package instead of older, more low-level techniques.

The java.util.concurrent package is fairly large. The best guide to its contents is likely the excellent book Java Concurrency in Practice, written by Brian Goetz and other experts. The following is a very brief sketch of the most important elements in java.util.concurrent.

The most important idea is the separation of tasks and the policy for their execution. A task (an informal term) comes in two flavours:

For executing tasks, there are 3 important interfaces, which are linked in an inheritance chain. Starting at the top level, they are:

The Executors factory class returns implementations of ExecutorService and ScheduledExecutorService.

When you need to be informed of the result of a task after it completes, you will likely use these items:

Finally, the following are used to synchronize between threads:

Some example code:

Concurrency uses many specialized terms. Some definitions:

Here's the lifecycle of a task submitted to an Executor:

See Also :
Modernize old code