Java – why use private locks instead of internal locks?

In reading about synchronization, I encountered "monitoring mode" to encapsulate variable states

Here is the sample code

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

}

Is it better to have a private lock in any way than an internal lock?

Solution

Yes - this means that you can see all the code that might get locked (regardless of the possibility of reflection)

If you lock this (which I assume you refer to through "internal locking"), other code can execute:

MonitorLock foo = new MonitorLock();
synchronized(foo) {
    // Do some stuff
}

This code may be far away from monitorlock itself, and may call other methods, which will take out the monitor It's easy to enter the deadlock area here because you can't easily see what locks are going to be obtained

With a "private" lock, you can easily view every piece of code that acquires the lock because they are all in monitorlock Therefore, it is easier to infer this locking

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>