Synchronizing on a class field synchronizes not on the field itself, but on the object assigned to it. So reassigning a field in a block synchronized on that field's contents immediately opens the block up to access by another thread.
private String color = "red";
private void doSomething(){
synchronized(color) { // lock is actually on object instance "red" referred to by the color variable
//...
color = "green"; // Noncompliant; other threads now allowed into this block
// ...
}
}
private String color = "red";
private Object lockObj = new Object();
private void doSomething(){
synchronized(lockObj) {
//...
color = "green";
// ...
}
}