[英]Can I access the Lock used by a synchronized block in Java?
Having a simple List: 有一个简单的列表:
private final List<Item> lst = new ArrayList();
When I need synchronization, I used to do the following: 当我需要同步时,我曾经做以下事情:
synchronized (lst) {
// Some code
}
Now, I need to create a Condition
object using Lock.newCondition()
, can I access the underlying lock used by synchronized{}
to use it to create my condition, or should I remove synchronized blocks and use a custom Lock
object ? 现在,我需要使用
Lock.newCondition()
创建一个Condition
对象,是否可以访问Lock.newCondition()
synchronized{}
使用的基础锁来使用它创建条件,还是应该删除同步块并使用自定义Lock
对象?
If you need a Condition object, is a clear sign that intrinsic locking are not enough for you. 如果您需要一个Condition对象,则明确表明内部锁定不足以满足您的需求。 You will need to use
您将需要使用
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Anyway, if you are worried about performances, that is not a problem with modern virtual machines. 无论如何,如果您担心性能,那么对于现代虚拟机来说这不是问题。 Explicit locking perform as well as intrinsic one.
显式锁定与固有锁定一样好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.