Unsafe: removing the monitorEnter/monitorExit/tryMonitorEnter methods
Mandy Chung
mandy.chung at oracle.com
Thu Feb 27 21:15:45 UTC 2014
On 2/27/14 4:29 AM, Paul Sandoz wrote:
>> This will allocate about 10 Thread objects per second until the other thread finally reaches the synchronized read() method in BufferedInputStream...
>> >
> I like it.
I like it too.
> I do have a slight preference for Mandy's solution, see below, but i am not sure we can guarantee it is supported on all test platforms.
The hotspot VM implementation supports it on all platforms. Note that
this cost is not small - it stops the world and up call to JVM.
Mandy
>
> Paul.
>
> try {
> while (!isMonitorLockHeld(monitor)) {
> Thread.sleep(1);
> }
> } catch (UnsupportedOperationException e) {
> // Back up plan?
> Thread.sleep(TimeUnit.SECONDS.toMillis(1));
> }
>
> /**
> * Returns {@code true} if and only if the a thread holds the
> * monitor lock on the specified object.
> *
> * @throws java.lang.UnsupportedOperationException if monitoring of
> * object monitor use is not supported
> */
> public static boolean isMonitorLockHeld(Object o) {
> int oihc = System.identityHashCode(o);
> ThreadMXBean tmxbean = ManagementFactory.getThreadMXBean();
> ThreadInfo[] tinfos = tmxbean.dumpAllThreads(true, false);
>
> for (ThreadInfo ti : tinfos) {
> for (MonitorInfo mi : ti.getLockedMonitors()) {
> if (mi.getIdentityHashCode() == oihc)
> return true;
> }
> }
> return false;
> }
>
More information about the core-libs-dev
mailing list