If key is not already associated with a value or if key is associated with zero, associate it with newValue. Returns the previous value associated with key, or zero if there was no mapping for key.
(K key, long newValue)
| 403 | */ |
| 404 | |
| 405 | long putIfAbsent(K key, long newValue) { |
| 406 | while (true) { |
| 407 | AtomicLong atomic = map.get(key); |
| 408 | if (atomic == null) { |
| 409 | atomic = map.putIfAbsent(key, new AtomicLong(newValue)); |
| 410 | if (atomic == null) { |
| 411 | return 0L; |
| 412 | } |
| 413 | // atomic is now non-null; fall through |
| 414 | } |
| 415 | long oldValue = atomic.get(); |
| 416 | if (oldValue == 0L) { |
| 417 | // don't compareAndSet a zero |
| 418 | if (map.replace(key, atomic, new AtomicLong(newValue))) { |
| 419 | return 0L; |
| 420 | } |
| 421 | // atomic replaced |
| 422 | continue; |
| 423 | } |
| 424 | return oldValue; |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | /** |
| 429 | * If {@code (key, expectedOldValue)} is currently in the map, this method replaces {@code |