- ConcurrentHashMap putIfAbsent : atomicity when followed by a get() call
- private final ConcurrentHashMap<K, V> map = new ConcurrentHashMap<K, V>();
- public V getExampleOne(K key) {
- map.putIfAbsent(key, new Object());
- return map.get(key);
- }
- public V getExampleTwo(K key) {
- return map.putIfAbsent(key, new Object());
- }
- if (!map.containsKey(key))
- return map.put(key, value); [1]
- return map.get(key);
- public V getExampleThree(K key) {
- Object object = new Object();
- V value = locks.putIfAbsent(key, object);
- if (value == null)
- return object;
- return value;
- }
- public V getExampleOne(K key) {
- for(Object o = null, ret = null; (ret = map.get(key)) == null; )
- map.putIfAbsent(key, o == null ? o = new Object() : o);
- return ret;
- }
- public V getExampleThree(K key) {
- Object o = new Object();
- map.putIfAbsent(key, o);
- Object ret = map.get(key);
- return ret == null ? o : ret;
- }
- public synchronized V getExampleOne(K key) {
- map.putIfAbsent(key, new Object());
- return map.get(key);
- }
- private final ConcurrentHashMap<String, Object> map = new ConcurrentHashMap();
- /*
- * Guaranteed to return the object replaced.
- *
- * Note that by the time this method returns another thread
- * may have already replaced the object again.
- *
- * All we can guarantee here is that the return value WAS
- * associated with the key in the map at the time the entry was
- * replaced.
- *
- * A null return implies that either a null object was associated
- * with the specified key or there was no entry in the map for
- * the specified key wih 'null' as it's 'value'.
- */
- public Object consistentReplace ( String key, Object newValue ) {
- Object oldValue = map.get(key);
- while ( !map.replace(key, oldValue, newValue) ) {
- // Failed to replace because someone got in there before me.
- oldValue = map.get(key);
- }
- return oldValue;
- }