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.
这篇关于为什么使用私有锁而不是内在锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么使用私有锁而不是内在锁?
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
