ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentMap.java
Revision: 1.50
Committed: Sat Dec 7 17:26:50 2013 UTC (10 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.49: +7 -5 lines
Log Message:
fix replaceAll code sample

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8 import java.util.Map;
9 import java.util.Objects;
10 import java.util.function.BiConsumer;
11 import java.util.function.BiFunction;
12 import java.util.function.Function;
13
14 /**
15 * A {@link java.util.Map} providing thread safety and atomicity
16 * guarantees.
17 *
18 * <p>To support atomic usages, ConcurrentMaps are expected not to
19 * allow {@code null} as a legal value (and to throw exceptions upon
20 * attempted insertions). This enables a return value of {@code null}
21 * to unambiguously indicate the absence of a mapping. This interface
22 * does not strictly forbid implementations that may hold {@code null}
23 * values. However, in any that do so, a {@code null} value must bear
24 * the same interpretation as the absence of a mapping in order to
25 * conform to method atomicity requirements. Further, any that do so
26 * must override all default method implementations.
27 *
28 * <p>Several methods (for example {@link #putIfAbsent}) inherited
29 * from {@link Map} do not have default implementations, and so must
30 * be provided by implementations of this interface, even though they
31 * have (non-atomic) default implementations in the {@link Map}
32 * interface.
33 *
34 * <p>Memory consistency effects: As with other concurrent
35 * collections, actions in a thread prior to placing an object into a
36 * {@code ConcurrentMap} as a key or value
37 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
38 * actions subsequent to the access or removal of that object from
39 * the {@code ConcurrentMap} in another thread.
40 *
41 * <p>This interface is a member of the
42 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
43 * Java Collections Framework</a>.
44 *
45 * @since 1.5
46 * @author Doug Lea
47 * @param <K> the type of keys maintained by this map
48 * @param <V> the type of mapped values
49 */
50 public interface ConcurrentMap<K,V> extends Map<K,V> {
51
52 /**
53 * {@inheritDoc}
54 *
55 * @implNote The default implementation returns the result of
56 * {@code get(key)} unless {@code null}, in which case it returns
57 * the given defaultValue.
58 *
59 * @throws ClassCastException {@inheritDoc}
60 * @throws NullPointerException {@inheritDoc}
61 * @since 1.8
62 */
63 @Override
64 default V getOrDefault(Object key, V defaultValue) {
65 V v;
66 return ((v = get(key)) != null) ? v : defaultValue;
67 }
68
69 /**
70 * {@inheritDoc}
71 *
72 * @implSpec The default implementation is equivalent to, for this
73 * {@code map}:
74 * <pre> {@code
75 * for (Map.Entry<K,V> entry : map.entrySet())
76 * action.accept(entry.getKey(), entry.getValue());
77 * }</pre>
78 *
79 * @implNote The default implementation assumes that {@code
80 * IllegalStateException} thrown by {@code getKey()} or {@code
81 * getValue()} indicates that the entry no longer exists.
82 * Operation continues for subsequent entries.
83 *
84 * @throws NullPointerException {@inheritDoc}
85 * @since 1.8
86 */
87 @Override
88 default void forEach(BiConsumer<? super K, ? super V> action) {
89 Objects.requireNonNull(action);
90 for (Map.Entry<K,V> entry : entrySet()) {
91 K k;
92 V v;
93 try {
94 k = entry.getKey();
95 v = entry.getValue();
96 } catch (IllegalStateException ise) {
97 // this usually means the entry is no longer in the map.
98 continue;
99 }
100 action.accept(k, v);
101 }
102 }
103
104 /**
105 * If the specified key is not already associated
106 * with a value, associates it with the given value.
107 * This is equivalent to
108 * <pre> {@code
109 * if (map.containsKey(key))
110 * return map.get(key);
111 * else
112 * return map.put(key, value);
113 * }</pre>
114 *
115 * except that the action is performed atomically.
116 *
117 * @implNote There is no default implementation.
118 *
119 * @param key key with which the specified value is to be associated
120 * @param value value to be associated with the specified key
121 * @return the previous value associated with the specified key, or
122 * {@code null} if there was no mapping for the key.
123 * (A {@code null} return can also indicate that the map
124 * previously associated {@code null} with the key,
125 * if the implementation supports null values.)
126 * @throws UnsupportedOperationException if the {@code put} operation
127 * is not supported by this map
128 * @throws ClassCastException if the class of the specified key or value
129 * prevents it from being stored in this map
130 * @throws NullPointerException if the specified key or value is null,
131 * and this map does not permit null keys or values
132 * @throws IllegalArgumentException if some property of the specified key
133 * or value prevents it from being stored in this map
134 */
135 V putIfAbsent(K key, V value);
136
137 /**
138 * Removes the entry for a key only if currently mapped to a given value.
139 * This is equivalent to
140 * <pre> {@code
141 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
142 * map.remove(key);
143 * return true;
144 * } else
145 * return false;
146 * }</pre>
147 *
148 * except that the action is performed atomically.
149 *
150 * @implNote There is no default implementation.
151 *
152 * @param key key with which the specified value is associated
153 * @param value value expected to be associated with the specified key
154 * @return {@code true} if the value was removed
155 * @throws UnsupportedOperationException if the {@code remove} operation
156 * is not supported by this map
157 * @throws ClassCastException if the key or value is of an inappropriate
158 * type for this map
159 * (<a href="../Collection.html#optional-restrictions">optional</a>)
160 * @throws NullPointerException if the specified key or value is null,
161 * and this map does not permit null keys or values
162 * (<a href="../Collection.html#optional-restrictions">optional</a>)
163 */
164 boolean remove(Object key, Object value);
165
166 /**
167 * Replaces the entry for a key only if currently mapped to a given value.
168 * This is equivalent to
169 * <pre> {@code
170 * if (map.containsKey(key) && Objects.equals(map.get(key), oldValue)) {
171 * map.put(key, newValue);
172 * return true;
173 * } else
174 * return false;
175 * }</pre>
176 *
177 * except that the action is performed atomically.
178 *
179 * @implNote There is no default implementation.
180 *
181 * @param key key with which the specified value is associated
182 * @param oldValue value expected to be associated with the specified key
183 * @param newValue value to be associated with the specified key
184 * @return {@code true} if the value was replaced
185 * @throws UnsupportedOperationException if the {@code put} operation
186 * is not supported by this map
187 * @throws ClassCastException if the class of a specified key or value
188 * prevents it from being stored in this map
189 * @throws NullPointerException if a specified key or value is null,
190 * and this map does not permit null keys or values
191 * @throws IllegalArgumentException if some property of a specified key
192 * or value prevents it from being stored in this map
193 */
194 boolean replace(K key, V oldValue, V newValue);
195
196 /**
197 * Replaces the entry for a key only if currently mapped to some value.
198 * This is equivalent to
199 * <pre> {@code
200 * if (map.containsKey(key)) {
201 * return map.put(key, value);
202 * } else
203 * return null;
204 * }</pre>
205 *
206 * except that the action is performed atomically.
207 *
208 * @implNote There is no default implementation.
209 *
210 * @param key key with which the specified value is associated
211 * @param value value to be associated with the specified key
212 * @return the previous value associated with the specified key, or
213 * {@code null} if there was no mapping for the key.
214 * (A {@code null} return can also indicate that the map
215 * previously associated {@code null} with the key,
216 * if the implementation supports null values.)
217 * @throws UnsupportedOperationException if the {@code put} operation
218 * is not supported by this map
219 * @throws ClassCastException if the class of the specified key or value
220 * prevents it from being stored in this map
221 * @throws NullPointerException if the specified key or value is null,
222 * and this map does not permit null keys or values
223 * @throws IllegalArgumentException if some property of the specified key
224 * or value prevents it from being stored in this map
225 */
226 V replace(K key, V value);
227
228 /**
229 * {@inheritDoc}
230 *
231 * @implSpec
232 * <p>The default implementation is equivalent to, for this {@code map}:
233 * <pre> {@code
234 * for (Map.Entry<K,V> entry : map.entrySet()) {
235 * K k;
236 * V v;
237 * do {
238 * k = entry.getKey();
239 * v = entry.getValue();
240 * } while (!map.replace(k, v, function.apply(k, v)));
241 * }</pre>
242 *
243 * The default implementation may retry these steps when multiple
244 * threads attempt updates, and may call the function multiple
245 * times.
246 *
247 * @throws UnsupportedOperationException {@inheritDoc}
248 * @throws NullPointerException {@inheritDoc}
249 * @throws ClassCastException {@inheritDoc}
250 * @throws IllegalArgumentException {@inheritDoc}
251 * @since 1.8
252 */
253 @Override
254 default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
255 Objects.requireNonNull(function);
256 forEach((k,v) -> {
257 while (!replace(k, v, function.apply(k, v))) {
258 // v changed or k is gone
259 if ( (v = get(k)) == null) {
260 // k is no longer in the map.
261 break;
262 }
263 }
264 });
265 }
266
267 /**
268 * {@inheritDoc}
269 *
270 * @implSpec
271 * The default implementation is equivalent to the following steps for this
272 * {@code map}, then returning the current value or {@code null} if now
273 * absent:
274 *
275 * <pre> {@code
276 * if (map.get(key) == null) {
277 * V newValue = mappingFunction.apply(key);
278 * if (newValue != null)
279 * return map.putIfAbsent(key, newValue);
280 * }
281 * }</pre>
282 *
283 * The default implementation may retry these steps when multiple
284 * threads attempt updates, and may call the mapping function
285 * multiple times.
286 *
287 * @throws UnsupportedOperationException {@inheritDoc}
288 * @throws ClassCastException {@inheritDoc}
289 * @throws NullPointerException {@inheritDoc}
290 * @since 1.8
291 */
292 @Override
293 default V computeIfAbsent(K key,
294 Function<? super K, ? extends V> mappingFunction) {
295 Objects.requireNonNull(mappingFunction);
296 V v, newValue;
297 return ((v = get(key)) == null &&
298 (newValue = mappingFunction.apply(key)) != null &&
299 (v = putIfAbsent(key, newValue)) == null) ? newValue : v;
300 }
301
302 /**
303 * {@inheritDoc}
304 *
305 * @implSpec
306 * The default implementation is equivalent to performing the following
307 * steps for this {@code map}, then returning the current value or
308 * {@code null} if now absent. :
309 *
310 * <pre> {@code
311 * if (map.get(key) != null) {
312 * V oldValue = map.get(key);
313 * V newValue = remappingFunction.apply(key, oldValue);
314 * if (newValue != null)
315 * map.replace(key, oldValue, newValue);
316 * else
317 * map.remove(key, oldValue);
318 * }
319 * }</pre>
320 *
321 * The default implementation may retry these steps when multiple
322 * threads attempt updates, and may call the remapping function
323 * multiple times.
324 *
325 * @throws UnsupportedOperationException {@inheritDoc}
326 * @throws ClassCastException {@inheritDoc}
327 * @throws NullPointerException {@inheritDoc}
328 * @since 1.8
329 */
330 @Override
331 default V computeIfPresent(K key,
332 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
333 Objects.requireNonNull(remappingFunction);
334 V oldValue;
335 while ((oldValue = get(key)) != null) {
336 V newValue = remappingFunction.apply(key, oldValue);
337 if (newValue != null) {
338 if (replace(key, oldValue, newValue))
339 return newValue;
340 } else if (remove(key, oldValue))
341 return null;
342 }
343 return oldValue;
344 }
345
346 /**
347 * {@inheritDoc}
348 *
349 * @implSpec
350 * The default implementation is equivalent to performing the following
351 * steps for this {@code map}, then returning the current value or
352 * {@code null} if absent:
353 *
354 * <pre> {@code
355 * V oldValue = map.get(key);
356 * V newValue = remappingFunction.apply(key, oldValue);
357 * if (oldValue != null ) {
358 * if (newValue != null)
359 * map.replace(key, oldValue, newValue);
360 * else
361 * map.remove(key, oldValue);
362 * } else {
363 * if (newValue != null)
364 * map.putIfAbsent(key, newValue);
365 * else
366 * return null;
367 * }
368 * }</pre>
369 *
370 * The default implementation may retry these steps when multiple
371 * threads attempt updates, and may call the remapping function
372 * multiple times.
373 *
374 * @throws UnsupportedOperationException {@inheritDoc}
375 * @throws ClassCastException {@inheritDoc}
376 * @throws NullPointerException {@inheritDoc}
377 * @since 1.8
378 */
379 @Override
380 default V compute(K key,
381 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
382 Objects.requireNonNull(remappingFunction);
383 V oldValue = get(key);
384 for (;;) {
385 V newValue = remappingFunction.apply(key, oldValue);
386 if (newValue == null) {
387 // delete mapping
388 if (oldValue != null || containsKey(key)) {
389 // something to remove
390 if (remove(key, oldValue)) {
391 // removed the old value as expected
392 return null;
393 }
394
395 // some other value replaced old value. try again.
396 oldValue = get(key);
397 } else {
398 // nothing to do. Leave things as they were.
399 return null;
400 }
401 } else {
402 // add or replace old mapping
403 if (oldValue != null) {
404 // replace
405 if (replace(key, oldValue, newValue)) {
406 // replaced as expected.
407 return newValue;
408 }
409
410 // some other value replaced old value. try again.
411 oldValue = get(key);
412 } else {
413 // add (replace if oldValue was null)
414 if ((oldValue = putIfAbsent(key, newValue)) == null) {
415 // replaced
416 return newValue;
417 }
418
419 // some other value replaced old value. try again.
420 }
421 }
422 }
423 }
424
425
426 /**
427 * {@inheritDoc}
428 *
429 * @implSpec
430 * The default implementation is equivalent to performing the following
431 * steps for this {@code map}, then returning the current value or
432 * {@code null} if absent:
433 *
434 * <pre> {@code
435 * V oldValue = map.get(key);
436 * V newValue = (oldValue == null) ? value :
437 * remappingFunction.apply(oldValue, value);
438 * if (newValue == null)
439 * map.remove(key);
440 * else
441 * map.put(key, newValue);
442 * }</pre>
443 *
444 * The default implementation may retry these steps when multiple
445 * threads attempt updates, and may call the remapping function
446 * multiple times.
447 *
448 * @throws UnsupportedOperationException {@inheritDoc}
449 * @throws ClassCastException {@inheritDoc}
450 * @throws NullPointerException {@inheritDoc}
451 * @since 1.8
452 */
453 @Override
454 default V merge(K key, V value,
455 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
456 Objects.requireNonNull(remappingFunction);
457 Objects.requireNonNull(value);
458 V oldValue = get(key);
459 for (;;) {
460 if (oldValue != null) {
461 V newValue = remappingFunction.apply(oldValue, value);
462 if (newValue != null) {
463 if (replace(key, oldValue, newValue))
464 return newValue;
465 } else if (remove(key, oldValue)) {
466 return null;
467 }
468 oldValue = get(key);
469 } else {
470 if ((oldValue = putIfAbsent(key, value)) == null) {
471 return value;
472 }
473 }
474 }
475 }
476 }