1 |
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> |
2 |
<html> <head> |
3 |
<title>Concurrency Utilities</title> |
4 |
<!-- |
5 |
Written by Doug Lea with assistance from members of JCP JSR-166 |
6 |
Expert Group and released to the public domain, as explained at |
7 |
http://creativecommons.org/licenses/publicdomain |
8 |
--> |
9 |
</head> |
10 |
|
11 |
<body> |
12 |
|
13 |
<p> Utility classes commonly useful in concurrent programming. This |
14 |
package includes a few small standardized extensible frameworks, as |
15 |
well as some classes that provide useful functionality and are |
16 |
otherwise tedious or difficult to implement. Here are brief |
17 |
descriptions of the main components. See also the <tt>locks</tt> and |
18 |
<tt>atomic</tt> packages. |
19 |
|
20 |
<h2>Executors</h2> |
21 |
|
22 |
<b>Interfaces.</b> {@link java.util.concurrent.Executor} is a simple |
23 |
standardized interface for defining custom thread-like subsystems, |
24 |
including thread pools, asynchronous IO, and lightweight task |
25 |
frameworks. Depending on which concrete Executor class is being used, |
26 |
tasks may execute in a newly created thread, an existing |
27 |
task-execution thread, or the thread calling <tt>execute()</tt>, and |
28 |
may execute sequentially or concurrently. {@link |
29 |
java.util.concurrent.ExecutorService} provides a more complete |
30 |
asynchronous task execution framework. An ExecutorService manages |
31 |
queuing and scheduling of tasks, and allows controlled shutdown. The |
32 |
{@link java.util.concurrent.ScheduledExecutorService} subinterface |
33 |
and associated interfaces add support for delayed and periodic task execution. |
34 |
ExecutorServices provide methods arranging asynchronous execution of |
35 |
any function expressed as {@link java.util.concurrent.Callable}, the |
36 |
result-bearing analog of {@link java.lang.Runnable}. A {@link |
37 |
java.util.concurrent.Future} returns the results of a function, allows |
38 |
determination of whether execution has completed, and provides a means to |
39 |
cancel execution. A {@link java.util.concurrent.RunnableFuture} is |
40 |
a Future that possesses a <tt>run</tt> method that upon execution, |
41 |
sets its results. |
42 |
|
43 |
<p> |
44 |
|
45 |
<b>Implementations.</b> Classes {@link |
46 |
java.util.concurrent.ThreadPoolExecutor} and {@link |
47 |
java.util.concurrent.ScheduledThreadPoolExecutor} provide tunable, |
48 |
flexible thread pools. The {@link java.util.concurrent.Executors} |
49 |
class provides factory methods for the most common kinds and |
50 |
configurations of Executors, as well as a few utility methods for |
51 |
using them. Other utilities based on Executors include the concrete |
52 |
class {@link java.util.concurrent.FutureTask} providing a common |
53 |
extensible implementation of Futures, and {@link |
54 |
java.util.concurrent.ExecutorCompletionService}, that assists in |
55 |
coordinating the processing of groups of asynchronous tasks. |
56 |
|
57 |
<h2>Queues</h2> |
58 |
|
59 |
The java.util.concurrent {@link |
60 |
java.util.concurrent.ConcurrentLinkedQueue} class supplies an |
61 |
efficient scalable thread-safe non-blocking FIFO queue. Five |
62 |
implementations in java.util.concurrent support the extended {@link |
63 |
java.util.concurrent.BlockingQueue} interface, that defines blocking |
64 |
versions of put and take: {@link |
65 |
java.util.concurrent.LinkedBlockingQueue}, {@link |
66 |
java.util.concurrent.ArrayBlockingQueue}, {@link |
67 |
java.util.concurrent.SynchronousQueue}, {@link |
68 |
java.util.concurrent.PriorityBlockingQueue}, and {@link |
69 |
java.util.concurrent.DelayQueue}. The different classes cover the most |
70 |
common usage contexts for producer-consumer, messaging, parallel |
71 |
tasking, and related concurrent designs. The {@link |
72 |
java.util.concurrent.BlockingDeque} interface extends |
73 |
<tt>BlockingQueue</tt> to support both FIFO and LIFO (stack-based) |
74 |
operations. Class {@link java.util.concurrent.LinkedBlockingDeque} |
75 |
provides an implementation. |
76 |
|
77 |
|
78 |
<h2>Timing</h2> |
79 |
|
80 |
The {@link java.util.concurrent.TimeUnit} class provides multiple |
81 |
granularities (including nanoseconds) for specifying and controlling |
82 |
time-out based operations. Most classes in the package contain |
83 |
operations based on time-outs in addition to indefinite waits. In all |
84 |
cases that time-outs are used, the time-out specifies the minimum time |
85 |
that the method should wait before indicating that it |
86 |
timed-out. Implementations make a "best effort" to detect |
87 |
time-outs as soon as possible after they occur. However, an indefinite |
88 |
amount of time may elapse between a time-out being detected and a |
89 |
thread actually executing again after that time-out. All methods |
90 |
that accept timeout parameters treat values less than or equal to |
91 |
zero to mean not to wait at all. To wait "forever", you can use |
92 |
a value of <tt>Long.MAX_VALUE</tt>. |
93 |
|
94 |
<h2>Synchronizers</h2> |
95 |
|
96 |
Four classes aid common special-purpose synchronization idioms. |
97 |
{@link java.util.concurrent.Semaphore} is a classic concurrency tool. |
98 |
{@link java.util.concurrent.CountDownLatch} is a very simple yet very |
99 |
common utility for blocking until a given number of signals, events, |
100 |
or conditions hold. A {@link java.util.concurrent.CyclicBarrier} is a |
101 |
resettable multiway synchronization point useful in some styles of |
102 |
parallel programming. An {@link java.util.concurrent.Exchanger} allows |
103 |
two threads to exchange objects at a rendezvous point, and is useful |
104 |
in several pipeline designs. |
105 |
|
106 |
<h2>Concurrent Collections</h2> |
107 |
|
108 |
Besides Queues, this package supplies Collection implementations |
109 |
designed for use in multithreaded contexts: |
110 |
{@link java.util.concurrent.ConcurrentHashMap}, |
111 |
{@link java.util.concurrent.ConcurrentSkipListMap}, |
112 |
{@link java.util.concurrent.ConcurrentSkipListSet}, |
113 |
{@link java.util.concurrent.CopyOnWriteArrayList}, and |
114 |
{@link java.util.concurrent.CopyOnWriteArraySet}. |
115 |
When many threads are expected to access a given collection, |
116 |
a <tt>ConcurrentHashMap</tt> is normally preferable to |
117 |
a synchronized <tt>HashMap</tt>, and a |
118 |
<tt>ConcurrentSkipListMap</tt> is normally preferable |
119 |
to a synchronized <tt>TreeMap</tt>. A |
120 |
<tt>CopyOnWriteArrayList</tt> is preferable to |
121 |
a synchronized <tt>ArrayList</tt> when the expected number of reads |
122 |
and traversals greatly outnumber the number of updates to a list. |
123 |
|
124 |
<p>The "Concurrent" prefix used with some classes in this package is a |
125 |
shorthand indicating several differences from similar "synchronized" |
126 |
classes. For example <tt>java.util.Hashtable</tt> and |
127 |
<tt>Collections.synchronizedMap(new HashMap())</tt> are |
128 |
synchronized. But {@link java.util.concurrent.ConcurrentHashMap} is |
129 |
"concurrent". A concurrent collection is thread-safe, but not |
130 |
governed by a single exclusion lock. In the particular case of |
131 |
ConcurrentHashMap, it safely permits any number of concurrent reads as |
132 |
well as a tunable number of concurrent writes. "Synchronized" classes |
133 |
can be useful when you need to prevent all access to a collection via |
134 |
a single lock, at the expense of poorer scalability. In other cases in |
135 |
which multiple threads are expected to access a common collection, |
136 |
"concurrent" versions are normally preferable. And unsynchronized |
137 |
collections are preferable when either collections are unshared, or |
138 |
are accessible only when holding other locks. |
139 |
|
140 |
<p> Most concurrent Collection implementations (including most Queues) |
141 |
also differ from the usual java.util conventions in that their Iterators |
142 |
provide <em>weakly consistent</em> rather than fast-fail traversal. A |
143 |
weakly consistent iterator is thread-safe, but does not necessarily |
144 |
freeze the collection while iterating, so it may (or may not) reflect |
145 |
any updates since the iterator was created. |
146 |
|
147 |
<a name="MemoryVisibility"> |
148 |
<h2> Memory Consistency Properties </h2> |
149 |
|
150 |
<a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html"> |
151 |
Chapter 17 of the Java Language Specification</a> defines the |
152 |
<i>happens-before</i> relation on memory operations such as reads and |
153 |
writes of shared variables. The results of a write by one thread are |
154 |
guaranteed to be visible to a read by another thread only if the write |
155 |
operation <i>happens-before</i> the read operation. The |
156 |
{@code synchronized} and {@code volatile} constructs, as well as the |
157 |
{@code Thread.start()} and {@code Thread.join()} methods, can form |
158 |
<i>happens-before</i> relationships. In particular: |
159 |
|
160 |
<ul> |
161 |
<li>Each action in a thread <i>happens-before</i> every action in that |
162 |
thread that comes later in the program's order. |
163 |
|
164 |
<li>An unlock ({@code synchronized} block or method exit) of a |
165 |
monitor <i>happens-before</i> every subsequent lock ({@code synchronized} |
166 |
block or method entry) of that same monitor. And because |
167 |
the <i>happens-before</i> relation is transitive, all actions |
168 |
of a thread prior to unlocking <i>happen-before</i> all actions |
169 |
subsequent to any thread locking that monitor. |
170 |
|
171 |
<li>A write to a {@code volatile} field <i>happens-before</i> every |
172 |
subsequent read of that same field. Writes and reads of |
173 |
{@code volatile} fields have similar memory consistency effects |
174 |
as entering and exiting monitors, but do <em>not</em> entail |
175 |
mutual exclusion locking. |
176 |
|
177 |
<li>A call to {@code start} on a thread <i>happens-before</i> any action in the |
178 |
started thread. |
179 |
|
180 |
<li>All actions in a thread <i>happen-before</i> any other thread |
181 |
successfully returns from a {@code join} on that thread. |
182 |
|
183 |
</ul> |
184 |
|
185 |
|
186 |
The methods of all classes in {@code java.util.concurrent} and its |
187 |
subpackages extend these guarantees to higher-level |
188 |
synchronization. In particular: |
189 |
|
190 |
<ul> |
191 |
|
192 |
<li>Actions in a thread prior to placing an object into any concurrent |
193 |
collection <i>happen-before</i> actions subsequent to the access or |
194 |
removal of that element from the collection in another thread. |
195 |
|
196 |
<li>Actions in a thread prior to the submission of a {@code Runnable} |
197 |
to an {@code Executor} <i>happen-before</i> its execution begins. |
198 |
Similarly for {@code Callables} submitted to an {@code ExecutorService}. |
199 |
|
200 |
<li>Actions taken by the asynchronous computation represented by a |
201 |
{@code Future} <i>happen-before</i> actions subsequent to the |
202 |
retrieval of the result via {@code Future.get()} in another thread. |
203 |
|
204 |
<li>Actions prior to "releasing" synchronizer methods such as |
205 |
{@code Lock.unlock}, {@code Semaphore.release}, and |
206 |
{@code CountDownLatch.countDown} <i>happen-before</i> actions |
207 |
subsequent to a successful "acquiring" method such as |
208 |
{@code Lock.lock}, {@code Semaphore.acquire}, |
209 |
{@code Condition.await}, and {@code CountDownLatch.await} on the |
210 |
same synchronizer object in another thread. |
211 |
|
212 |
<li>For each pair of threads that successfully exchange objects via |
213 |
an {@code Exchanger}, actions prior to the {@code exchange()} |
214 |
in each thread <i>happen-before</i> those subsequent to the |
215 |
corresponding {@code exchange()} in another thread. |
216 |
|
217 |
<li>Actions prior to calling {@code CyclicBarrier.await} |
218 |
<i>happen-before</i> actions performed by the barrier action, and |
219 |
actions performed by the barrier action <i>happen-before</i> actions |
220 |
subsequent to a successful return from the corresponding {@code await} |
221 |
in other threads. |
222 |
|
223 |
</ul> |
224 |
|
225 |
@since 1.5 |
226 |
|
227 |
</body> </html> |