You're asking the wrong question. Whether the variable is local is irrelevant, as shown in the following example:
class Test {
private Map<String, String> map = new HashMap<>();
public void put(String key, String value) {
Map<String, String> localMap = this.map;
synchronized (localMap) {
localMap.put(key, value);
}
}
}
The local reference is actually necessary if there's a possibility that the field could be replaced while you're in the synchronized
block.
So the real question is whether you should ever lock on a private value, that is, an object not available to other threads. You may think your example demonstrates such a case, but per the JLS, the autoboxed Integer
12
is cached, meaning you're actually synchronizing on a global value.
Now, assuming you have a local value that's actually private to its thread, there's generally no point in synchronizing on it, and I think some analyzers will warn you if you try. However, see here and here for a possible exception.