Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 9th, 2012  |  syntax: None  |  size: 1.88 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. ConcurrentHashMap putIfAbsent : atomicity when followed by a get() call
  2. private final ConcurrentHashMap<K, V> map = new ConcurrentHashMap<K, V>();
  3.  
  4. public V getExampleOne(K key) {
  5.     map.putIfAbsent(key, new Object());
  6.     return map.get(key);
  7. }
  8.        
  9. public V getExampleTwo(K key) {
  10.     return map.putIfAbsent(key, new Object());
  11. }
  12.        
  13. if (!map.containsKey(key))
  14.    return map.put(key, value);     [1]
  15. return map.get(key);
  16.        
  17. public V getExampleThree(K key) {
  18.     Object object = new Object();
  19.     V value = locks.putIfAbsent(key, object);
  20.     if (value == null)
  21.         return object;
  22.     return value;
  23. }
  24.        
  25. public V getExampleOne(K key) {
  26.     for(Object o = null, ret = null; (ret = map.get(key)) == null; )
  27.         map.putIfAbsent(key, o == null ? o = new Object() : o);
  28.     return ret;
  29. }
  30.        
  31. public V getExampleThree(K key) {
  32.     Object o = new Object();
  33.     map.putIfAbsent(key, o);
  34.     Object ret = map.get(key);
  35.     return ret == null ? o : ret;
  36. }
  37.        
  38. public synchronized V getExampleOne(K key) {
  39.     map.putIfAbsent(key, new Object());
  40.     return map.get(key);
  41. }
  42.        
  43. private final ConcurrentHashMap<String, Object> map = new ConcurrentHashMap();
  44.  
  45. /*
  46.  * Guaranteed to return the object replaced.
  47.  *
  48.  * Note that by the time this method returns another thread
  49.  * may have already replaced the object again.
  50.  *
  51.  * All we can guarantee here is that the return value WAS
  52.  * associated with the key in the map at the time the entry was
  53.  * replaced.
  54.  *
  55.  * A null return implies that either a null object was associated
  56.  * with the specified key or there was no entry in the map for
  57.  * the specified key wih 'null' as it's 'value'.
  58.  */
  59. public Object consistentReplace ( String key, Object newValue ) {
  60.   Object oldValue = map.get(key);
  61.   while ( !map.replace(key, oldValue, newValue) ) {
  62.     // Failed to replace because someone got in there before me.
  63.     oldValue = map.get(key);
  64.   }
  65.   return oldValue;
  66. }