Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added some text courtesy Tim Halloran

...

Code Block
bgColor#FFcccc
private Integer semaphorelock = new Integer(0);
synchronized(semaphorelock) { /* ... */ }

This is because the thread that holds a lock on the nonfinal field object can modify the field's value, allowing another thread that is blocked on the unmodified value to resume, at the same time, contending for the lock with a third thread that is blocked on the modified value. It is insecure to synchronize on a mutable field because this is equivalent to synchronizing on the field's contents. This is a lock mutability problem as opposed to the lock sharing issue specific to string literals and boxed primitives.

...

Code Block
bgColor#ccccff
private final Integer semaphorelock = new Integer(0);
synchronized(semaphorelock) { /* ... */ }

As long as the lock object is final, it is acceptable for the referenced object to be mutable. In this compliant solution, the Integer object happens to be immutable by definition.

...

Code Block
bgColor#FFcccc
final Lock lock = new ReentrantLock();
synchronized(lock) { /* ... */ }

This problem usually comes up in practice when refactoring from intrinsic locking to the java.util.concurrent utilities.

Compliant Solution (lock() and unlock())

...