Object intrinsic monitor as java.util.concurrent.Lock

半城伤御伤魂 提交于 2019-12-12 14:33:37

问题


I believe it could be very useful to be able to use an object's monitor as a Lock. That is :

synchronized(object) {
    ...
}

would be equivalent to :

lock.lock();
try {
    ...
} finally {
    lock.unlock();
}

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

or something like :

LockSupport.getIntrinsicMonitorObject(Object of);

Questions :

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

  • Is there some solution to do it using existing JRE classes ?

  • Would a JSR on this make sense ?


回答1:


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

*that's in Java 8 but I think it was already there in Java 7



来源:https://stackoverflow.com/questions/22375370/object-intrinsic-monitor-as-java-util-concurrent-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!