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

前端 未结 6 1915
佛祖请我去吃肉
佛祖请我去吃肉 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:28

    By keeping a pre-initialized value for each thread you can improve on the accepted answer:

    Set initial = new HashSet();
    ...
    Set set = map.putIfAbsent(name, initial);
    if (set == null) {
        set = initial;
        initial = new HashSet();
    }
    set.add(Y);
    

    I recently used this with AtomicInteger map values rather than Set.

提交回复
热议问题