为什么使用私有锁而不是内在锁?

Why use private lock over intrinsic lock?(为什么使用私有锁而不是内在锁?)

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

问题描述

在阅读有关同步的内容时,我遇到了监控模式"来封装可变状态.

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).

如果您锁定 this(我假设您指的是内在锁"),那么其他代码可以这样做:

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.

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

本文标题为:为什么使用私有锁而不是内在锁?

基础教程推荐