2013年6月20日 星期四

ConcurrentMap使用

import java.util.concurrent.*;

public class TestThread{

    public static void main(String[] args)
    {
        ConcurrentMap myMap = new ConcurrentHashMap();
     Object o = new Object();
     o = myMap.putIfAbsent("1", "one");
     System.out.println( o );
     o = myMap.putIfAbsent("2", "two");
     System.out.println( o );
     o = myMap.putIfAbsent("3", "333");
     System.out.println( o );
     o = myMap.putIfAbsent("3", "3");
     System.out.println( o );
     System.out.println( myMap );
    }

}

回傳

null
null
null
333
{1=one, 3=333, 2=two}


使用putIfAbsent 可以發現若前面有key相同的話,則不會覆蓋之前的key value,

並且回傳333也就是之前相同key的value。

API文件:


putIfAbsent
public V putIfAbsent(K key,
            V value)
If the specified key is not already associated with a value, associate it with the given value. This is equivalent to
   if (!map.containsKey(key))
       return map.put(key, value);
   else
       return map.get(key);
except that the action is performed atomically.
Specified by:
putIfAbsent in interface ConcurrentMap
Parameters:
key - key with which the specified value is to be associated
value - value to be associated with the specified key
Returns:
the previous value associated with the specified key, or null if there was no mapping for the key
Throws:
NullPointerException - if the specified key or value is null

沒有留言: