ConcurrentHashMap: avoid extra object creation with “putIfAbsent”?

后端 未结 7 2024
北海茫月
北海茫月 2020-12-12 19:10

I am aggregating multiple values for keys in a multi-threaded environment. The keys are not known in advance. I thought I would do something like this:

class         


        
相关标签:
7条回答
  • 2020-12-12 20:12

    Created two versions based on Gene's answer

    public  static <K,V> void putIfAbsetMultiValue(ConcurrentHashMap<K,List<V>> entries, K key, V value) {
        List<V> values = entries.get(key);
        if (values == null) {
            values = Collections.synchronizedList(new ArrayList<V>());
            List<V> values2 = entries.putIfAbsent(key, values);
            if (values2 != null)
                values = values2;
        }
        values.add(value);
    }
    
    public  static <K,V> void putIfAbsetMultiValueSet(ConcurrentMap<K,Set<V>> entries, K key, V value) {
        Set<V> values = entries.get(key);
        if (values == null) {
            values = Collections.synchronizedSet(new HashSet<V>());
            Set<V> values2 = entries.putIfAbsent(key, values);
            if (values2 != null)
                values = values2;
        }
        values.add(value);
    }
    

    It works well

    0 讨论(0)
提交回复
热议问题