Why is this an issue?

Instances of value-based classes, which are pooled and potentially reused, should not be used for synchronization. If they are, it can cause unrelated threads to deadlock with unhelpful stacktraces.

Within the JDK, types which should not be used for synchronization include:

How to fix it

Replace instances of value-based classes with a new object instance to synchronize on.

Code examples

Noncompliant code example

private static final Boolean bLock = Boolean.FALSE;
private static final Integer iLock = Integer.valueOf(0);
private static final String sLock = "LOCK";
private static final List<String> listLock = List.of("a", "b", "c", "d");

public void doSomething() {

  synchronized(bLock) {  // Noncompliant
      ...
  }
  synchronized(iLock) {  // Noncompliant
      ...
  }
  synchronized(sLock) {  // Noncompliant
      ...
  }
  synchronized(listLock) {  // Noncompliant
      ...
  }

Compliant solution

private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
private static final Object lock3 = new Object();
private static final Object lock4 = new Object();

public void doSomething() {

  synchronized(lock1) { // Compliant
      ...
  }
  synchronized(lock2) { // Compliant
      ...
  }
  synchronized(lock3) { // Compliant
      ...
  }
  synchronized(lock4) { // Compliant
      ...
  }

Resources