I\'m looking at some legacy code which has the following idiom:
Map myMap = someGlobalInstance.getMap();
synchronized (myMap) {
item =
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.