/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package jdk.testlibrary; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.concurrent.TimeoutException; public class TestThread extends Thread { private Runnable runnable; public Runnable getRunnable() { return runnable; } public TestThread(Runnable target, String name) { super(target, name); this.runnable = target; } public TestThread(Runnable target) { super(target); this.runnable = target; } public TestThread(ThreadGroup group, Runnable target, String name, long stackSize) { super(group, target, name, stackSize); this.runnable = target; } public TestThread(ThreadGroup group, Runnable target, String name) { super(group, target, name); this.runnable = target; } public TestThread(ThreadGroup group, Runnable target) { super(group, target); this.runnable = target; } private Throwable uncaught; @Override public void run() { try { super.run(); } catch (Throwable t) { uncaught = t; } } public Throwable getUncaught() { return uncaught; } public void joinAndThrow() throws InterruptedException, Throwable { join(); if (uncaught != null) { throw uncaught; } } public void joinAndThrow(long timeout) throws InterruptedException, Throwable { join(timeout); if (isAlive()) { throw new TimeoutException(); } if (uncaught != null) { throw uncaught; } } public Throwable joinAndReturn() throws InterruptedException { join(); if (uncaught != null) { return uncaught; } return null; } public Throwable joinAndReturn(long timeout) throws InterruptedException { join(timeout); if (isAlive()) { return new TimeoutException(); } if (uncaught != null) { return uncaught; } return null; } /** * Use java.lang.management to find out if this thread is waiting */ public void waitUntilBlockingOnObject(Thread.State state, Object o) { String want = o == null ? null : o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o)); ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); while (isAlive()) { ThreadInfo ti = tmx.getThreadInfo(getId()); if (ti.getThreadState() == state && (want == null || want.equals(ti.getLockName()))) { return; } try { Thread.sleep(1); } catch (InterruptedException e) { } } } public void waitUntilInNative() { ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); while (isAlive()) { ThreadInfo ti = tmx.getThreadInfo(getId()); if (ti.isInNative()) { return; } try { Thread.sleep(1); } catch (InterruptedException e) { } } } }