Map和ConcurrentMap

ConcurrentMap为map增加原子方法,用于同步操作。

V putIfAbsent(K key, V value);

如果map中还没有key就添加,有key就直接返回key对应的value

     * <pre>
     *   if (!map.containsKey(key))
     *       return map.put(key, value);

//put方法the previous value associated with key, or null if there was no mapping for key
     *   else
     *       return map.get(key);</pre>

使用示例:确保并发情况下同一个type不好创建多次

List<WebSocketMessageInbound> connects = connections.get(type);
        if (null == connects) {
            connects = new ArrayList<WebSocketMessageInbound>();
            connects=connections.putIfAbsent(type, connects);//connects is null
            connects=connections.get(type);////connects is not null
        }
        return connects;

 

boolean remove(Object key, Object value);

if (map.containsKey(key) &amp;&amp; map.get(key).equals(value)) {
     *       map.remove(key);
     *       return true;
     *   } else return false;

 

boolean replace(K key, V oldValue, V newValue);

 

 

V replace(K key, V value);

 

Map

put 方法 return:the previous value associated with key, or null if there was no mapping for key

返回的是上一次的值而不是本次set的值

 

List<WebSocketMessageInbound> connects = connections.get(type);
        if (null == connects) {
            connects = new ArrayList<WebSocketMessageInbound>();
            connects=connections.putIfAbsent(type, connects);//connects is null
            connects=connections.get(type);////connects is not null
        }
        return connects;

你可能感兴趣的:(Concurrent)