Advantages to using private lock object

来源:互联网 发布:js留言板 编辑:程序博客网 时间:2024/05/29 13:52

There are advantages to using a private lock object instead of an object’s intrinsic lock (or any other publicly accessible lock).

Making the lock object private encapsulates the lock so that client code cannot acquire it, whereas a publicly accessible lock allows client code to participate in its synchronization policy (correctly or incorrectly). Clients that improperly acquire another object’s lock could cause liveness problems, and verifying that a publicly accessible lock is properly used requires examining the entire program rather than a single class.

Good Example:

public class PrivateLock {private final Object myLock = new Object();Widget widget;void someMethod() {synchronized (myLock) {// Access or modify the state of widget}}}

Bad Example:

public class PrivateLock {Widget widget;synchronized void someMethod() {// Access or modify the state of widget}}


"Java concurrency in practice" 4.2.1


Related posts:

Is there any advantage of Java monitor pattern in synchronization

Java Monitor Pattern