Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
int lock = 0;
private final Integer Lock = lock; // Boxed primitive Lock will be shared

public void doSomething() {
  synchronized(Lock) { 
    // ...
  }
}

...

This noncompliant code example incorrectly uses a ReentrantLock as the lock object.

Code Block
bgColor#FFcccc
private final Lock lock = new ReentrantLock();

public void doSomething() {
  synchronized(lock) {
    // ... 
  }
}

...

Instead of using the intrinsic locks of objects that implement the Lock interface, including ReentrantLock, use the lock() and unlock() methods provided by the Lock interface.

Code Block
bgColor#ccccff
private final Lock lock = new ReentrantLock();

public void doSomething() {
  lock.lock();
  try {
    // ...
  } finally {
    lock.unlock();
  }
}

...