Concurrency-2
High Level Concurrency Objects
- Lock objects support locking idioms that simplify many concurrent applications.
- Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
- Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
- Atomic variables have features that minimize synchronization and help avoid memory consistency errors.
- ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
Lock Objects
Synchronized code relies on a simple kind of reentrant lock.
This kind of lock is easy to use, but has many limitations. More sophisticated locking idioms are supported by the java.util.concurrent.locks package.
The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock.
Executors
I This works well for small applications, but in large-scale applications, it makes sense to separate thread management and creation from the rest of the application. Objects that encapsulate these functions are known as executors. The following subsections describe executors in detail.
Executor Interfaces define the three executor object types.
Thread Pools are the most common kind of executor implementation.
Fork/Join is a framework (new in JDK 7) for taking advantage of multiple processors.
Executor Interfaces
The java.util.concurrent
package defines three executor interfaces:
Executor, a simple interface that supports launching new tasks.
ExecutorService, a subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.
ScheduledExecutorService, a subinterface of ExecutorService, supports future and/or periodic execution of tasks.
Typically, variables that refer to executor objects are declared as one of these three interface types, not with an executor class type.
Executors
The Executor interface provides a single method, execute
.
ExecutorService
The ExecutorService interface supplements execute with a similar, but more versatile submit()
method.
Like execute
, submit
accepts Runnable objects, but also accepts Callable objects, which allow the task to return a value.
ExecutorService also provides methods for submitting large collections of Callable objects. Finally, ExecutorService provides a number of methods for managing the shutdown of the executor. To support immediate shutdown, tasks should handle interrupts
correctly.
The ScheduledExecutorService Interface
The ScheduledExecutorService interface supplements the methods of its parent ExecutorService with schedule, which executes a Runnable or Callable task after a specified delay. In addition, the interface defines scheduleAtFixedRate
and scheduleWithFixedDelay
, which executes specified tasks repeatedly, at defined intervals.
Thread Pools
Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads.
A simple way to create an executor that uses a fixed thread pool is to invoke the newFixedThreadPool
factory method in java.util.concurrent.Executors
This class also provides the following factory methods:
The newCachedThreadPool
method creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks.
The newSingleThreadExecutor
method creates an executor that executes a single task at a time.
Several factory methods are ScheduledExecutorService
versions of the above executors.
Fork/Join
Cocurrent Collections
The java.util.concurrent
package includes a number of additions to the Java Collections Framework. These are most easily categorized by the collection interfaces provided:
-
BlockingQueue
defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue. -
ConcurrentMap
is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent. Making these operations atomic helps avoid synchronization. The standard general-purpose implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap. -
ConcurrentNavigableMap
is a subinterface of ConcurrentMap that supports approximate matches. The standard general-purpose implementation of ConcurrentNavigableMap isConcurrentSkipListMap
, which is a concurrent analog of TreeMap.
Atomic Variables
The java.util.concurrent.atomic package defines classes that support atomic operations on single variables.
Concurrent Random Numbers
In JDK 7, java.util.concurrent includes a convenience class, ThreadLocalRandom, for applications that expect to use random numbers from multiple threads or ForkJoinTasks.
For concurrent access, using ThreadLocalRandom instead of Math.random() results in less contention and, ultimately, better performance.
All you need to do is call ThreadLocalRandom.current(), then call one of its methods to retrieve a random number. Here is one example:
int r = ThreadLocalRandom.current() .nextInt(4, 77);
Future Readings
- Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea. A comprehensive work by a leading expert, who's also the architect of the Java platform's concurrency framework.
- Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. A practical guide designed to be accessible to the novice.
- Effective Java Programming Language Guide (2nd Edition) by Joshua Bloch. Though this is a general programming guide, its chapter on threads contains essential "best practices" for concurrent programming.
- Concurrency: State Models & Java Programs (2nd Edition), by Jeff Magee and Jeff Kramer. An introduction to concurrent programming through a combination of modeling and practical examples.
- Java Concurrent Animated: Animations that show usage of concurrency features.
网友评论