ConcurrentHashMap: avoid extra object creation with “putIfAbsent”?

后端 未结 7 2045
北海茫月
北海茫月 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:02

    In the end, I implemented a slight modification of @Bohemian's answer. His proposed solution overwrites the values variable with the putIfAbsent call, which creates the same problem I had before. The code that seems to work looks like this:

        public void record(String key, String value) {
            List values = entries.get(key);
            if (values == null) {
                values = Collections.synchronizedList(new ArrayList());
                List values2 = entries.putIfAbsent(key, values);
                if (values2 != null)
                    values = values2;
            }
            values.add(value);
        }
    

    It's not as elegant as I'd like, but it's better than the original that creates a new ArrayList instance at every call.

提交回复
热议问题