Synchronized and local copies of variables

后端 未结 4 2055

I\'m looking at some legacy code which has the following idiom:

Map myMap = someGlobalInstance.getMap();
synchronized (myMap) {
    item =         


        
4条回答
  •  被撕碎了的回忆
    2021-02-19 13:57

    Alex is correct in that adding a synchronized wrapper by calling Collections.synchronizedMap(Map) is a typical approach here. However, if you take this approach there may still be situations where you need to synchronized on the Map's lock; e.g. when iterating over the map.

    Map syncMap = Collections.synchronizedMap(new HashMap());
    
    // Synchronized on map to prevent ConcurrentModificationException whilst iterating.
    synchronized (syncMap) {
      for (Map.Entry entry : syncMap.entrySet()) {
        // Do work
      }
    }
    

    In your example, the warning from IDEA can be ignored, as it's evident that your local variable: map is retrieved from somewhere else (someGlobalInstance) rather than being created within the method, and can therefore potentially be accessed from other threads.

提交回复
热议问题