为什么使用私有锁而不是内部锁? [英] Why use private lock over intrinsic lock?

查看:112
本文介绍了为什么使用私有锁而不是内部锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读同步时,我遇到了监控模式以封装可变状态。

While reading about synchronization, I came across "monitor pattern" to encapsulate mutable states.

以下是示例代码

   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:

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

这段代码可能离 MonitorLock 本身很远,可能会调用其他方法来反过来取出监视器。这里很容易进入死锁区域,因为你无法轻易看到将要获得哪些锁定。

This code may be a long way away from MonitorLock itself, and may call other methods which in turn take out monitors. It's easy to get into deadlock territory here, because you can't easily see what's going to acquire which locks.

使用私人锁定,您可以轻松看到获取该锁的每一段代码,因为它全部在 MonitorLock 中。因此更容易推断锁定。

With a "private" lock, you can easily see every piece of code which acquires that lock, because it's all within MonitorLock. It's therefore easier to reason about that lock.

这篇关于为什么使用私有锁而不是内部锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆