Synchronized objects should not be re-assigned in the same synchronized
block because the references to the synchronized object would be lost. When this happens, different threads might operate on different objects rather than the same synchronized object as they expect.
1private void assignSynchronizedObjectNoncompliant() {
2 // Noncompliant: synchronized objects re-assigned in the same synchronized block.
3 synchronized (mutex) {
4 mutex = new Object();
5 doSomething(mutex);
6 }
7}
1private void assignSynchronizingObjectCompliant() {
2 // Compliant: avoids re-assigning to synchronized objects in the same synchronized block.
3 synchronized (mutex) {
4 mutex_one = new Object();
5 doSomething(mutex);
6 }
7}