On Feb 27, 2014, at 12:52 PM, Peter Levart <peter.lev...@gmail.com> wrote: > > Ok, then what about the following: > > static boolean isLocked(final Object monitor, final long millis) throws > InterruptedException { > return new Thread() { > volatile boolean unlocked; > > @Override > public void run() { > synchronized (monitor) { unlocked = true; } > } > > boolean isLocked() throws InterruptedException { > start(); > join(millis); > return !unlocked; > } > }.isLocked(); > } > > > // and usage it like: > > while (!isLocked(s, 100L)) { > Thread.sleep(100L); > } > > > 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 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. 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; }