Should you check if the map containsKey before using ConcurrentMap's putIfAbsent

前端 未结 6 1929
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 09:02

I have been using Java\'s ConcurrentMap for a map that can be used from multiple threads. The putIfAbsent is a great method and is much easier to read/write than using stand

6条回答
  •  执念已碎
    2020-12-07 09:25

    Concurrency is hard. If you are going to bother with concurrent maps instead of straightforward locking, you might as well go for it. Indeed, don't do lookups more than necessary.

    Set set = map.get(name);
    if (set == null) {
        final Set value = new HashSet();
        set = map.putIfAbsent(name, value);
        if (set == null) {
            set = value;
        }
    }
    

    (Usual stackoverflow disclaimer: Off the top of my head. Not tested. Not compiled. Etc.)

    Update: 1.8 has added computeIfAbsent default method to ConcurrentMap (and Map which is kind of interesting because that implementation would be wrong for ConcurrentMap). (And 1.7 added the "diamond operator" <>.)

    Set set = map.computeIfAbsent(name, n -> new HashSet<>());
    

    (Note, you are responsible for the thread-safety of any operations of the HashSets contained in the ConcurrentMap.)

提交回复
热议问题