简体   繁体   English

为什么使用私有锁而非内部锁?

[英]Why use private lock over intrinsic lock?

While reading about synchronization, I came across "monitor pattern" to encapsulate mutable states. 在阅读有关同步的过程中,我遇到了“监控模式”来封装可变状态。

The following 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 in any way to have a private lock instead of the intrinsic lock? 以任何方式拥有私有锁而不是内在锁更好吗?

Yes - it means you can see all the code which could possibly acquire that lock (leaving aside the possibility of reflection). 是的 - 这意味着你可以看到所有可能获得锁定的代码 (不考虑反射的可能性)。

If you lock on this (which is what I assume you're referring to by "the intrinsic lock") then other code can do: 如果您锁定this (这是我假设您通过“内部锁定”引用的),那么其他代码可以执行:

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

This code may be a long way away from MonitorLock itself, and may call other methods which in turn take out monitors. 此代码可能距离MonitorLock本身很远,可能会调用其他方法,而这些方法又会取出监视器。 It's easy to get into deadlock territory here, because you can't easily see what's going to acquire which locks. 在这里很容易进入死锁区域,因为你无法轻易看到将要获得哪些锁定。

With a "private" lock, you can easily see every piece of code which acquires that lock, because it's all within MonitorLock . 使用“私有”锁定,您可以轻松查看获取该锁定的每一段代码 ,因为它们都在MonitorLock It's therefore easier to reason about that lock. 因此,更容易推理出这种锁定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM