if (foo.needsProcessing()) {
synchronized (foo) {
foo.process(); // foo's state may be changed here
}
}
I think there is a race condition in the above fragment that could result in foo.process() occasionally being called twice on the same object. It should be:
synchronized (foo) {
if (foo.needsProcessing()) {
foo.process(); // foo's state may be changed here
}
}
Is this really that bad to synchronize on locals?
It is not bad to synchronize on locals per se. The real issues are:
-
whether the different threads are synchronizing on the correct objects to achieve proper synchronization, and
-
whether something else could cause problems by synchronizing on those objects.