Java synchronized block vs. Collections.synchronizedMap

后端 未结 7 1902
天涯浪人
天涯浪人 2020-11-28 03:35

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

public class MyClass {
  private static Map

        
7条回答
  •  离开以前
    2020-11-28 03:45

    That looks correct to me. If I were to change anything, I would stop using the Collections.synchronizedMap() and synchronize everything the same way, just to make it clearer.

    Also, I'd replace

      if (synchronizedMap.containsKey(key)) {
        synchronizedMap.get(key).add(value);
      }
      else {
        List valuesList = new ArrayList();
        valuesList.add(value);
        synchronizedMap.put(key, valuesList);
      }
    

    with

    List valuesList = synchronziedMap.get(key);
    if (valuesList == null)
    {
      valuesList = new ArrayList();
      synchronziedMap.put(key, valuesList);
    }
    valuesList.add(value);
    

提交回复
热议问题