Versions Compared

Key

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

...

Code Block
bgColor#ccccff
public class SomeObject {
  private final Object lock = new Object(); // private lock object

  public void changeValue() {
    synchronized (lock) { // Locks on the private Object
      // ...
    }
  }
}

For more details on using the private Object lock refer to CON02-J. Always synchronize on the appropriate object. There is some performance impact associated with using block synchronization instead of method synchronization but the difference is usually negligible. In the presence of statements that do not require synchronization amongst those that do, block synchronization tends to be a better performer.

Using a private lock may only be achieved with block synchronization, as method synchronization always uses the object's intrinsic lock. However, block synchronization is also preferred over method synchronization, because it is easy to move operations out of the synchronized block when they might take a long time and they are not truly a critical section.

...