问题
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