Unexpected re-assignment of synchronized objects High

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.

Detector ID
java/reassign-synchronized-object@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

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}

Compliant example

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}