Trying to synchronize method within runnable

后端 未结 4 1212
清歌不尽
清歌不尽 2020-12-21 22:45

I have a ConcurrentMap that gets instantiated outside of my runnables, but shared and updated within / accross the runnables. My runnables need to be concurrent, but my conc

4条回答
  •  春和景丽
    2020-12-21 23:26

    You should avoid synchronizing when using a ConcurrentMap. It provides other methods for handling these types of operations. For this case the putIfAbsent method should be preferred over a contains and then a put.

    public void runAnalysis(int index) {
        if (concurrentMap.putIfAbsent(index, "thread " + thread) == null) {
            System.out.println("put " + index + " thread " + thread);
        } else {
            System.out.println("contains integer " + index);
        }
    }
    

提交回复
热议问题