I'm looking at some legacy code which has the following idiom:
Map<String, Boolean> myMap = someGlobalInstance.getMap();
synchronized (myMap) {
item = myMap.get(myKey);
}
The warning I get from Intelli-J's code inspections is:
Synchronization on local variable 'myMap'
Is this the appropriate synchronization and why?
Map<String, Boolean> myMap = someGlobalInstance.getMap();
synchronized (someGlobalInstance.getMap()) {
item = myMap.get(myKey);
}
The reason this is flagged as a problem is because synchronizing on local variables is usually a bad idea.
If the object returned by someGlobalInstance.getMap()
is always the same, then the synchronized block does in fact use that quasi-global objects monitor and the code produces the expected result.
I also agree with the suggestion to use a synchronized wrapper, if you only need to synchronize the get()
/put()
calls and don't have any bigger synchronized blocks. But make sure that the Map is only accessed via the wrapper or you'll have another chance for bugs.
Also note that if someGlobalInstance.getMap()
does not return the same object all the time, then even your second code example will not work correctly, it could even be worse than your original code since you could synchronize on a different object than the one you call get()
on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With