本文介绍了Java synchronized块与Collections.synchronizedMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是否设置为正确同步 synchronizedMap上的调用

Is the following code set up to correctly synchronize the calls on synchronizedMap?

public class MyClass {
  private static Map<String, List<String>> synchronizedMap = Collections.synchronizedMap(new HashMap<String, List<String>>());

  public void doWork(String key) {
    List<String> values = null;
    while ((values = synchronizedMap.remove(key)) != null) {
      //do something with values
    }
  }

  public static void addToMap(String key, String value) {
    synchronized (synchronizedMap) {
      if (synchronizedMap.containsKey(key)) {
        synchronizedMap.get(key).add(value);
      }
      else {
        List<String> valuesList = new ArrayList<String>();
        valuesList.add(value);
        synchronizedMap.put(key, valuesList);
      }
    }
  }
}

来自我的理解,我需要 addToMap()中的synchronized块,以防止另一个线程调用 remove() containsKey()在我通过调用 put()之前,但我不需要<$ c $中的同步块c> doWork()因为在 remove() addToMap()中的synchronized块c $ c>返回,因为我最初使用 Collections.synchronizedMap()创建了Map。那是对的吗?有没有更好的方法呢?

From my understanding, I need the synchronized block in addToMap() to prevent another thread from calling remove() or containsKey() before I get through the call to put() but I do not need a synchronized block in doWork() because another thread cannot enter the synchronized block in addToMap() before remove() returns because I created the Map originally with Collections.synchronizedMap(). Is that correct? Is there a better way to do this?

推荐答案

Collections.synchronizedMap()保证您要在地图上运行的每个原子操作都将被同步。

Collections.synchronizedMap() guarantees that each atomic operation you want to run on the map will be synchronized.

然而,必须在地图上同步运行两个(或更多)操作块。
是的 - 您正在正确同步。

Running two (or more) operations on the map however, must be synchronized in a block.So yes - you are synchronizing correctly.

这篇关于Java synchronized块与Collections.synchronizedMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:33