对象固有监视器为java.util.concurrent.Lock [英] Object intrinsic monitor as java.util.concurrent.Lock
问题描述
我相信能够将对象的监视器用作Lock
可能非常有用.那是:
I believe it could be very useful to be able to use an object's monitor as a Lock
. That is :
synchronized(object) {
...
}
等同于:
lock.lock();
try {
...
} finally {
lock.unlock();
}
据我所知,不可能使用Lock
接口实现此目的,因为同步仅发生在块中.
我看到的解决方案是使java.lang.Object
通过一种额外的方法得到充实
As far as i understand it, it is not possible to achieve this using Lock
interface since synchronization only happens in blocks.
A solution i see would be to have java.lang.Object
be enriched with an extra method
public Lock asLock/getIntrinsicMonitorObject(); // Name isn't perfect but i'm not asking for that
或类似的东西:
LockSupport.getIntrinsicMonitorObject(Object of);
问题:
Questions :
-
是否有一些充分的理由暂时无法执行此操作(我认为,某些
tryLock
当前无法通过同步进行的事实不是一个事实)
Is there some good reasons it isn't possible to do this for now (i consider the fact that some
tryLock
isn't currently possible with synchronization isn't one)
是否有一些使用现有JRE类的解决方案?
Is there some solution to do it using existing JRE classes ?
JSR对此有意义吗?
Would a JSR on this make sense ?
推荐答案
Unsafe
类*支持直接操作监视器的一些支持:
The Unsafe
class* has some support to directly manipulate monitors:
public native void monitorEnter(Object o);
public native void monitorExit(Object o);
public native boolean tryMonitorEnter(Object o);
*在Java 8中已经存在,但我认为Java 7中已经存在
这篇关于对象固有监视器为java.util.concurrent.Lock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!