Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.util.concurrent;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.Map;
A map containing long values that can be atomically updated. While writes to a traditional Map rely on put(K, V), the typical mechanism for writing to this map is addAndGet(K, long), which adds a long to the value currently associated with K. If a key has not yet been associated with a value, its implicit value is zero.

Most methods in this class treat absent values and zero values identically, as individually documented. Exceptions to this are containsKey(java.lang.Object), size(), isEmpty(), asMap, and toString().

Instances of this class may be used by multiple threads concurrently. All operations are atomic unless otherwise noted.

Note: If your values are always positive and less than 2^31, you may wish to use a com.google.common.collect.Multiset such as com.google.common.collect.ConcurrentHashMultiset instead. Warning: Unlike Multiset, entries whose values are zero are not automatically removed from the map. Instead they must be removed manually with removeAllZeros().

Author(s):
Charles Fry
Since:
11.0
 
 public final class AtomicLongMap<K> {
   private final ConcurrentHashMap<K, AtomicLongmap;
 
   private AtomicLongMap(ConcurrentHashMap<K, AtomicLongmap) {
     this. = checkNotNull(map);
   }

  
Creates an AtomicLongMap.
 
   public static <K> AtomicLongMap<K> create() {
     return new AtomicLongMap<K>(new ConcurrentHashMap<K, AtomicLong>());
   }

  
Creates an AtomicLongMap with the same mappings as the specified Map.
 
   public static <K> AtomicLongMap<K> create(Map<? extends K, ? extends Longm) {
     AtomicLongMap<K> result = create();
     result.putAll(m);
     return result;
   }

  
Returns the value associated with key, or zero if there is no value associated with key.
 
   public long get(K key) {
     AtomicLong atomic = .get(key);
     return atomic == null ? 0L : atomic.get();
   }

  
Increments by one the value currently associated with key, and returns the new value.
 
   public long incrementAndGet(K key) {
     return addAndGet(key, 1);
   }

  
Decrements by one the value currently associated with key, and returns the new value.
 
   public long decrementAndGet(K key) {
     return addAndGet(key, -1);
  }

  
Adds delta to the value currently associated with key, and returns the new value.
  public long addAndGet(K keylong delta) {
    outer: for (;;) {
      AtomicLong atomic = .get(key);
      if (atomic == null) {
        atomic = .putIfAbsent(keynew 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 (.replace(keyatomicnew AtomicLong(delta))) {
            return delta;
          }
          // atomic replaced
          continue outer;
        }
        long newValue = oldValue + delta;
        if (atomic.compareAndSet(oldValuenewValue)) {
          return newValue;
        }
        // value changed
      }
    }
  }

  
Increments by one the value currently associated with key, and returns the old value.
  public long getAndIncrement(K key) {
    return getAndAdd(key, 1);
  }

  
Decrements by one the value currently associated with key, and returns the old value.
  public long getAndDecrement(K key) {
    return getAndAdd(key, -1);
  }

  
Adds delta to the value currently associated with key, and returns the old value.
  public long getAndAdd(K keylong delta) {
    outer: for (;;) {
      AtomicLong atomic = .get(key);
      if (atomic == null) {
        atomic = .putIfAbsent(keynew AtomicLong(delta));
        if (atomic == null) {
          return 0L;
        }
        // atomic is now non-null; fall through
      }
      for (;;) {
        long oldValue = atomic.get();
        if (oldValue == 0L) {
          // don't compareAndSet a zero
          if (.replace(keyatomicnew AtomicLong(delta))) {
            return 0L;
          }
          // atomic replaced
          continue outer;
        }
        long newValue = oldValue + delta;
        if (atomic.compareAndSet(oldValuenewValue)) {
          return oldValue;
        }
        // value changed
      }
    }
  }

  
Associates newValue with key in this map, and returns the value previously associated with key, or zero if there was no such value.
  public long put(K keylong newValue) {
    outer: for (;;) {
      AtomicLong atomic = .get(key);
      if (atomic == null) {
        atomic = .putIfAbsent(keynew AtomicLong(newValue));
        if (atomic == null) {
          return 0L;
        }
        // atomic is now non-null; fall through
      }
      for (;;) {
        long oldValue = atomic.get();
        if (oldValue == 0L) {
          // don't compareAndSet a zero
          if (.replace(keyatomicnew AtomicLong(newValue))) {
            return 0L;
          }
          // atomic replaced
          continue outer;
        }
        if (atomic.compareAndSet(oldValuenewValue)) {
          return oldValue;
        }
        // value changed
      }
    }
  }

  
Copies all of the mappings from the specified map to this map. The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the specified map. The behavior of this operation is undefined if the specified map is modified while the operation is in progress.
  public void putAll(Map<? extends K, ? extends Longm) {
    for (Map.Entry<? extends K, ? extends Longentry : m.entrySet()) {
      put(entry.getKey(), entry.getValue());
    }
  }

  
Removes and returns the value associated with key. If key is not in the map, this method has no effect and returns zero.
  public long remove(K key) {
    AtomicLong atomic = .get(key);
    if (atomic == null) {
      return 0L;
    }
    for (;;) {
      long oldValue = atomic.get();
      if (oldValue == 0L || atomic.compareAndSet(oldValue, 0L)) {
        // only remove after setting to zero, to avoid concurrent updates
        .remove(keyatomic);
        // succeed even if the remove fails, since the value was already adjusted
        return oldValue;
      }
    }
  }

  
Removes all mappings from this map whose values are zero.

This method is not atomic: the map may be visible in intermediate states, where some of the zero values have been removed and others have not.

  public void removeAllZeros() {
    for (K key : .keySet()) {
      AtomicLong atomic = .get(key);
      if (atomic != null && atomic.get() == 0L) {
        .remove(keyatomic);
      }
    }
  }

  
Returns the sum of all values in this map.

This method is not atomic: the sum may or may not include other concurrent operations.

  public long sum() {
    long sum = 0L;
    for (AtomicLong value : .values()) {
      sum = sum + value.get();
    }
    return sum;
  }
  private transient Map<K, LongasMap;

  
Returns a live, read-only view of the map backing this AtomicLongMap.
  public Map<K, LongasMap() {
    Map<K, Longresult = ;
    return (result == null) ?  = createAsMap() : result;
  }
  private Map<K, LongcreateAsMap() {
    return Collections.unmodifiableMap(
        Maps.transformValues(new Function<AtomicLongLong>() {
          @Override
          public Long apply(AtomicLong atomic) {
            return atomic.get();
          }
        }));
  }

  
Returns true if this map contains a mapping for the specified key.
  public boolean containsKey(Object key) {
    return .containsKey(key);
  }

  
Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
  public int size() {
    return .size();
  }

  
Returns true if this map contains no key-value mappings.
  public boolean isEmpty() {
    return .isEmpty();
  }

  
Removes all of the mappings from this map. The map will be empty after this call returns.

This method is not atomic: the map may not be empty after returning if there were concurrent writes.

  public void clear() {
    .clear();
  }
  public String toString() {
    return .toString();
  }
  /*
   * ConcurrentMap operations which we may eventually add.
   *
   * The problem with these is that remove(K, long) has to be done in two phases by definition ---
   * first decrementing to zero, and then removing. putIfAbsent or replace could observe the
   * intermediate zero-state. Ways we could deal with this are:
   *
   * - Don't define any of the ConcurrentMap operations. This is the current state of affairs.
   *
   * - Define putIfAbsent and replace as treating zero and absent identically (as currently
   *   implemented below). This is a bit surprising with putIfAbsent, which really becomes
   *   putIfZero.
   *
   * - Allow putIfAbsent and replace to distinguish between zero and absent, but don't implement
   *   remove(K, long). Without any two-phase operations it becomes feasible for all remaining
   *   operations to distinguish between zero and absent. If we do this, then perhaps we should add
   *   replace(key, long).
   *
   * - Introduce a special-value private static final AtomicLong that would have the meaning of
   *   removal-in-progress, and rework all operations to properly distinguish between zero and
   *   absent.
   */

  
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.
  long putIfAbsent(K keylong newValue) {
    for (;;) {
      AtomicLong atomic = .get(key);
      if (atomic == null) {
        atomic = .putIfAbsent(keynew AtomicLong(newValue));
        if (atomic == null) {
          return 0L;
        }
        // atomic is now non-null; fall through
      }
      long oldValue = atomic.get();
      if (oldValue == 0L) {
        // don't compareAndSet a zero
        if (.replace(keyatomicnew AtomicLong(newValue))) {
          return 0L;
        }
        // atomic replaced
        continue;
      }
      return oldValue;
    }
  }

  
If (key, expectedOldValue) is currently in the map, this method replaces expectedOldValue with newValue and returns true; otherwise, this method returns false.

If expectedOldValue is zero, this method will succeed if (key, zero) is currently in the map, or if key is not in the map at all.

  boolean replace(K keylong expectedOldValuelong newValue) {
    if (expectedOldValue == 0L) {
      return putIfAbsent(keynewValue) == 0L;
    } else {
      AtomicLong atomic = .get(key);
      return (atomic == null) ? false : atomic.compareAndSet(expectedOldValuenewValue);
    }
  }

  
If (key, value) is currently in the map, this method removes it and returns true; otherwise, this method returns false.
  boolean remove(K keylong value) {
    AtomicLong atomic = .get(key);
    if (atomic == null) {
      return false;
    }
    long oldValue = atomic.get();
    if (oldValue != value) {
      return false;
    }
    if (oldValue == 0L || atomic.compareAndSet(oldValue, 0L)) {
      // only remove after setting to zero, to avoid concurrent updates
      .remove(keyatomic);
      // succeed even if the remove fails, since the value was already adjusted
      return true;
    }
    // value changed
    return false;
  }
New to GrepCode? Check out our FAQ X