Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized and local copies of variables

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);
}
like image 365
Epsilon Prime Avatar asked Nov 03 '09 22:11

Epsilon Prime


1 Answers

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.

like image 154
Joachim Sauer Avatar answered Oct 22 '22 15:10

Joachim Sauer