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.
这篇关于为什么使用私有锁而不是内在锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么使用私有锁而不是内在锁?


- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01