ConcurrentHashMap replace - top ranked examples from Open Source projects

These code examples were ranked by Codota’s semantic indexing as the best open source examples for ConcurrentHashMap replace method.

This code example shows how to use the following methods:get, putIfAbsent, replace
   * Adds {@code delta} to the value currently associated with {@code key}, and returns the new 
   * value. 
  public long addAndGet(K key, long delta) {
    outer: for (;;) { 
      AtomicLong atomic = map.get(key);
      if (atomic == null) {
        atomic = map.putIfAbsent(key, new AtomicLong(delta));
        if (atomic == null) {
          return delta;
        // atomic is now non-null; fall through 
      for (;;) { 
        long oldValue = atomic.get();
        if (oldValue == 0L) {
          // don't compareAndSet a zero 
          if (map.replace(key, atomic, new AtomicLong(delta))) {
            return delta;

replace Method Overview
Replaces the entry for a key only if currently mapped to a given value.
See Code Examples for other Java 8 ConcurrentHashMap Methods: