java.lang.Thread.State Java Examples

The following examples show how to use java.lang.Thread.State. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StackTraceSnapshotBuilderTest.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddStackTraceWaitRun() {
    System.out.println("add stacktrace : wait->run");

    addStacktrace(stack0, 0);
    setState(stack0[0], Thread.State.WAITING);
    
    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());

    setState(stack0[0], Thread.State.RUNNABLE);
    addStacktrace(stack0, 1000000);

    assertEquals(1000000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.RUNNABLE, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}
 
Example #2
Source File: SafeCallerImplTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private static String printThreadDump(String threadNamePrefix) {
    final StringBuilder sb = new StringBuilder();
    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE)) {
        if (!threadInfo.getThreadName().startsWith(threadNamePrefix)) {
            continue;
        }
        sb.append("\"");
        sb.append(threadInfo.getThreadName());
        sb.append("\" ");
        sb.append(State.class.getName());
        sb.append(": ");
        sb.append(threadInfo.getThreadState());
        for (final StackTraceElement stackTraceElement : threadInfo.getStackTrace()) {
            sb.append("\n    at ");
            sb.append(stackTraceElement);
        }
    }
    return sb.toString();
}
 
Example #3
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddStackTraceWaitBlocked() {
    System.out.println("add stacktrace : wait->blocked");

    addStacktrace(stack0, 0);
    setState(stack0[0], Thread.State.WAITING);

    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
    setState(stack0[0], Thread.State.BLOCKED);
    addStacktrace(stack0, 1000000);

    assertEquals(1000000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.BLOCKED, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}
 
Example #4
Source File: OverviewController.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** taken from sun.misc.VM
 * 
 * Returns Thread.State for the given threadStatus
 */
private static Thread.State toThreadState(int threadStatus) {
    if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
        return State.RUNNABLE;
    } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
        return State.BLOCKED;
    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
        return State.WAITING;
    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
        return State.TIMED_WAITING;
    } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
        return State.TERMINATED;
    } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
        return State.NEW;
    } else {
        return State.RUNNABLE;
    }
}
 
Example #5
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddStackTraceWaitWait() {
    System.out.println("add stacktrace : wait->wait");

    addStacktrace(stack0, 0);
    setState(stack0[0], Thread.State.WAITING);

    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
    addStacktrace(stack0, 1000000);

    assertEquals(1000000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}
 
Example #6
Source File: ThreadPrinter.java    From vjtools with Apache License 2.0 6 votes vote down vote up
public void printBlockedThreads() throws IOException {
	System.out.println("\n Stack trace of blocked threads:");
	int counter = 0;
	ThreadInfo[] threadInfos = view.vmInfo.getAllThreadInfo();
	for (ThreadInfo info : threadInfos) {
		if (info == null) {
			continue;
		}

		String threadName = info.getThreadName();

		if (Thread.State.BLOCKED.equals(info.getThreadState())
				&& (view.threadNameFilter == null || threadName.toLowerCase().contains(view.threadNameFilter))) {
			printSingleThread(info);
			counter++;
		}
	}

	System.out.println(" Total " + counter + " blocked threads");

	if (view.threadNameFilter != null) {
		System.out.println(" Thread name filter is:" + view.threadNameFilter);
	}
	System.out.flush();
}
 
Example #7
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddStacktraceWaitingPlus() {
    System.out.println("add stacktrace : waiting/plus");

    setState(stack0[0],Thread.State.WAITING);
    addStacktrace(stack0, 0);

    long timestamp = 500000;
    setState(stackPlus[2],Thread.State.RUNNABLE);

    addStacktrace(stackPlus, timestamp);

    assertEquals(Math.max(stack0.length, stackPlus.length), instance.threadIds.size());
    assertEquals(Math.max(elements0.length, elementsPlus.length), instance.methodInfos.size()-1);
    assertEquals(timestamp, instance.currentDumpTimeStamp);
}
 
Example #8
Source File: SafeCallerImplTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private static String createThreadDump(String threadNamePrefix) {
    final StringBuilder sb = new StringBuilder();
    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE)) {
        if (!threadInfo.getThreadName().startsWith(threadNamePrefix)) {
            continue;
        }
        sb.append("\"");
        sb.append(threadInfo.getThreadName());
        sb.append("\" ");
        sb.append(State.class.getName());
        sb.append(": ");
        sb.append(threadInfo.getThreadState());
        for (final StackTraceElement stackTraceElement : threadInfo.getStackTrace()) {
            sb.append("\n    at ");
            sb.append(stackTraceElement);
        }
    }
    return sb.toString();
}
 
Example #9
Source File: ConnectionManagerWatcherThreadTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void testEstablishConnectionSuccessfull() throws InterruptedException {
  ReentrantLock lock = new ReentrantLock();
  Condition condition = lock.newCondition();
  ConnectionManager connectionManagerMock = mock(ConnectionManager.class);
  when(connectionManagerMock.tryToEstablishConnection()).thenReturn(true);
  when(connectionManagerMock.getState()).thenReturn(ConnectionState.NEVER_CONNECTED);
  ConnectionManagerWatcherThread sut =
      new ConnectionManagerWatcherThread(lock, condition, connectionManagerMock, 50);
  sut.start();
  Thread.sleep(200);
  assertTrue(sut.isAlive());
  assertEquals(sut.isAlive(), sut.isRunning());
  verify(connectionManagerMock).tryToEstablishConnection();
  assertEquals(State.WAITING, sut.getState());
  killThreadAndVerifyState(sut);
  assertEquals(sut.isAlive(), sut.isRunning());
}
 
Example #10
Source File: ConnectionManagerWatcherThreadTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void testEstablishConnectionSuccessfullButLostAfterSomeTime() throws InterruptedException {
  ReentrantLock lock = new ReentrantLock();
  Condition condition = lock.newCondition();
  ConnectionManager connectionManagerMock = mock(ConnectionManager.class);
  when(connectionManagerMock.tryToEstablishConnection()).thenReturn(true);
  when(connectionManagerMock.getState()).thenReturn(ConnectionState.NEVER_CONNECTED);
  ConnectionManagerWatcherThread sut =
      new ConnectionManagerWatcherThread(lock, condition, connectionManagerMock, 50);
  sut.start();
  Thread.sleep(300);
  assertTrue(sut.isAlive());
  verify(connectionManagerMock).tryToEstablishConnection();
  assertEquals(State.WAITING, sut.getState());
  try {
    lock.lock();
    condition.signalAll();
  } finally {
    lock.unlock();
  }
  Thread.sleep(200);
  verify(connectionManagerMock, times(2)).tryToEstablishConnection();
  assertEquals(State.WAITING, sut.getState());
  killThreadAndVerifyState(sut);
}
 
Example #11
Source File: OverviewController.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/** taken from sun.misc.VM
 * 
 * Returns Thread.State for the given threadStatus
 */
private static Thread.State toThreadState(int threadStatus) {
    if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
        return State.RUNNABLE;
    } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
        return State.BLOCKED;
    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
        return State.WAITING;
    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
        return State.TIMED_WAITING;
    } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
        return State.TERMINATED;
    } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
        return State.NEW;
    } else {
        return State.RUNNABLE;
    }
}
 
Example #12
Source File: CameraSource.java    From OCR-Reader with MIT License 5 votes vote down vote up
/**
 * Releases the underlying receiver.  This is only safe to do after the associated thread
 * has completed, which is managed in camera source's release method above.
 */
@SuppressLint("Assert")
void release() {
    assert (mProcessingThread.getState() == State.TERMINATED);
    mDetector.release();
    mDetector = null;
}
 
Example #13
Source File: DrainFindDeadlockTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void checkState(Thread x, Thread y) {
    //            System.out.println("checkstate");
    boolean isXblocked = x.getState().equals(State.BLOCKED);
    boolean isYblocked = y.getState().equals(State.BLOCKED);
    long[] deadlockedThreads = null;

    if (isXblocked && isYblocked) {
        System.out.println("threads blocked");
        // they are both blocked, but this doesn't necessarily mean
        // they are deadlocked
        if (threadMXBeanDeadlockSupported) {
            System.out.println("checking for deadlock");
            deadlockedThreads = threadMXBean.findDeadlockedThreads();
        } else {
            System.out.println("Can't check for deadlock");
        }
        if (deadlockedThreads != null) {
            System.out.println("We detected a deadlock! ");
            ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(
                    deadlockedThreads, true, true);
            for (ThreadInfo threadInfo: threadInfos) {
                System.out.println(threadInfo);
            }
            throw new RuntimeException("TEST FAILED: Deadlock detected");
        }
        System.out.println("We may have a deadlock");
        Map<Thread, StackTraceElement[]> threadMap =
                Thread.getAllStackTraces();
        dumpStack(threadMap.get(x), x);
        dumpStack(threadMap.get(y), y);
    }
}
 
Example #14
Source File: ThreadUtilsTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsWaitingWithRunningThread() {
  final Thread runningThread = mockContext.mock(Thread.class, "Running Thread");

  mockContext.checking(new Expectations() {{
    oneOf(runningThread).getState();
    will(returnValue(State.RUNNABLE));
  }});

  assertFalse(ThreadUtils.isWaiting(runningThread));
}
 
Example #15
Source File: StackTraceSnapshotBuilderTest.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testAddStacktraceMinusWaitingThread() {
    System.out.println("add stacktrace : minus/waiting; additional thread");

    setState(stack0[1], Thread.State.WAITING);
    addStacktrace(stack0, 0);

    long timestamp = 500000;
    setState(stackMinus[0], Thread.State.WAITING);
    addStacktrace(stackMinus, timestamp);

    assertEquals(Math.max(stack0.length, stackMinus.length), instance.threadIds.size());
    assertEquals(Math.max(elements0.length, elementsMinus.length), instance.methodInfos.size()-1);
    assertEquals(timestamp, instance.currentDumpTimeStamp);
}
 
Example #16
Source File: ThreadUtilsTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsWaitingWithRunningThread() {
  final Thread runningThread = mockContext.mock(Thread.class, "Running Thread");

  mockContext.checking(new Expectations() {{
    oneOf(runningThread).getState();
    will(returnValue(State.RUNNABLE));
  }});

  assertFalse(ThreadUtils.isWaiting(runningThread));
}
 
Example #17
Source File: CameraSource.java    From android-vision with Apache License 2.0 5 votes vote down vote up
/**
 * Releases the underlying receiver.  This is only safe to do after the associated thread
 * has completed, which is managed in camera source's release method above.
 */
@SuppressLint("Assert")
void release() {
    assert (mProcessingThread.getState() == State.TERMINATED);
    mDetector.release();
    mDetector = null;
}
 
Example #18
Source File: CameraSource.java    From fuse-qreader with MIT License 5 votes vote down vote up
/**
 * Releases the underlying receiver.  This is only safe to do after the associated thread
 * has completed, which is managed in camera source's release method above.
 */
@SuppressLint("Assert")
void release() {
    assert (mProcessingThread.getState() == State.TERMINATED);
    mDetector.release();
    mDetector = null;
}
 
Example #19
Source File: DrainFindDeadlockTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
void checkState(Thread x, Thread y) {
    //            System.out.println("checkstate");
    boolean isXblocked = x.getState().equals(State.BLOCKED);
    boolean isYblocked = y.getState().equals(State.BLOCKED);
    long[] deadlockedThreads = null;

    if (isXblocked && isYblocked) {
        System.out.println("threads blocked");
        // they are both blocked, but this doesn't necessarily mean
        // they are deadlocked
        if (threadMXBeanDeadlockSupported) {
            System.out.println("checking for deadlock");
            deadlockedThreads = threadMXBean.findDeadlockedThreads();
        } else {
            System.out.println("Can't check for deadlock");
        }
        if (deadlockedThreads != null) {
            System.out.println("We detected a deadlock! ");
            ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(
                    deadlockedThreads, true, true);
            for (ThreadInfo threadInfo: threadInfos) {
                System.out.println(threadInfo);
            }
            throw new RuntimeException("TEST FAILED: Deadlock detected");
        }
        System.out.println("We may have a deadlock");
        Map<Thread, StackTraceElement[]> threadMap =
                Thread.getAllStackTraces();
        dumpStack(threadMap.get(x), x);
        dumpStack(threadMap.get(y), y);
    }
}
 
Example #20
Source File: GameReplayer.java    From Slyther with MIT License 5 votes vote down vote up
public GameReplayer(File file) {
    this.file = file;
    server = new WebSocketServer(new InetSocketAddress(8004)) {
        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            if (waitingForOpen) {
                thread = new Thread(GameReplayer.this, "Replayer");
                thread.start();   
                waitingForOpen = false;
            } else {
                Log.warn("Connection was attempted to be made during playback: {}", conn.getRemoteSocketAddress());
                conn.close();   
            }
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            waitingForClose = true;
            // Interrupt a long message delay
            while (waitingForClose) {
                if (thread.getState() == State.TIMED_WAITING) {
                    thread.interrupt();
                }
            }
        }

        @Override
        public void onMessage(WebSocket conn, String message) {}

        @Override
        public void onError(WebSocket conn, Exception ex) {
            if (ex instanceof BindException) {
                Log.catching(ex);
            }
        }
    };
    server.start();
}
 
Example #21
Source File: IODetectorTask.java    From LagMonitor with MIT License 5 votes vote down vote up
@Override
public void run() {
    //According to this post the thread is still in Runnable although it's waiting for
    //file/http resources
    //https://stackoverflow.com/questions/20795295/why-jstack-out-says-thread-state-is-runnable-while-socketread
    if (mainThread.getState() == State.RUNNABLE) {
        //Based on this post we have to check the top element of the stack
        //https://stackoverflow.com/questions/20891386/how-to-detect-thread-being-blocked-by-io
        StackTraceElement[] stackTrace = mainThread.getStackTrace();
        StackTraceElement topElement = stackTrace[stackTrace.length - 1];
        if (topElement.isNativeMethod()) {
            //Socket/SQL (connect) - java.net.DualStackPlainSocketImpl.connect0
            //Socket/SQL (read) - java.net.SocketInputStream.socketRead0
            //Socket/SQL (write) - java.net.SocketOutputStream.socketWrite0
            if (isElementEqual(topElement, "java.net.DualStackPlainSocketImpl", "connect0")
                    || isElementEqual(topElement, "java.net.SocketInputStream", "socketRead0")
                    || isElementEqual(topElement, "java.net.SocketOutputStream", "socketWrite0")) {
                actionManager.logCurrentStack("Server is performing {1} on the main thread. "
                        + "Properly caused by {0}", "java.net.SocketStream");
            } //File (in) - java.io.FileInputStream.readBytes
            //File (out) - java.io.FileOutputStream.writeBytes
            else if (isElementEqual(topElement, "java.io.FileInputStream", "readBytes")
                    || isElementEqual(topElement, "java.io.FileOutputStream", "writeBytes")) {
                actionManager.logCurrentStack("Server is performing {1} on the main thread. " +
                        "Properly caused by {0}", "java.io.FileStream");
            }
        }
    }
}
 
Example #22
Source File: Camera2Source.java    From Camera2Vision with Apache License 2.0 5 votes vote down vote up
/**
 * Releases the underlying receiver.  This is only safe to do after the associated thread
 * has completed, which is managed in camera source's release method above.
 */
@SuppressLint("Assert")
void release() {
    assert (mProcessingThread.getState() == State.TERMINATED);
    mDetector.release();
    mDetector = null;
}
 
Example #23
Source File: CameraSource.java    From Camera2Vision with Apache License 2.0 5 votes vote down vote up
/**
 * Releases the underlying receiver.  This is only safe to do after the associated thread
 * has completed, which is managed in camera source's release method above.
 */
@SuppressLint("Assert")
void release() {
    assert (mProcessingThread.getState() == State.TERMINATED);
    mDetector.release();
    mDetector = null;
}
 
Example #24
Source File: DrainFindDeadlockTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
void checkState(Thread x, Thread y) {
    //            System.out.println("checkstate");
    boolean isXblocked = x.getState().equals(State.BLOCKED);
    boolean isYblocked = y.getState().equals(State.BLOCKED);
    long[] deadlockedThreads = null;

    if (isXblocked && isYblocked) {
        System.out.println("threads blocked");
        // they are both blocked, but this doesn't necessarily mean
        // they are deadlocked
        if (threadMXBeanDeadlockSupported) {
            System.out.println("checking for deadlock");
            deadlockedThreads = threadMXBean.findDeadlockedThreads();
        } else {
            System.out.println("Can't check for deadlock");
        }
        if (deadlockedThreads != null) {
            System.out.println("We detected a deadlock! ");
            ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(
                    deadlockedThreads, true, true);
            for (ThreadInfo threadInfo: threadInfos) {
                System.out.println(threadInfo);
            }
            throw new RuntimeException("TEST FAILED: Deadlock detected");
        }
        System.out.println("We may have a deadlock");
        Map<Thread, StackTraceElement[]> threadMap =
                Thread.getAllStackTraces();
        dumpStack(threadMap.get(x), x);
        dumpStack(threadMap.get(y), y);
    }
}
 
Example #25
Source File: AndroidDebugBridge.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns whether the {@link AndroidDebugBridge} object is still connected to the adb daemon.
 */
public boolean isConnected() {
    MonitorThread monitorThread = MonitorThread.getInstance();
    if (mDeviceMonitor != null && monitorThread != null) {
        return mDeviceMonitor.isMonitoring() && monitorThread.getState() != State.TERMINATED;
    }
    return false;
}
 
Example #26
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddStackTraceRunnable() {
    System.out.println("add stacktrace : runnable");

    setState(stack0[0], Thread.State.RUNNABLE);

    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.RUNNABLE, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}
 
Example #27
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddStackTraceTerminated() {
    System.out.println("add stacktrace : terminated");

    setState(stack0[0], Thread.State.TERMINATED);

    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.TERMINATED, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}
 
Example #28
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddStackTraceBlocked() {
    System.out.println("add stacktrace : blocked");

    setState(stack0[0], Thread.State.BLOCKED);

    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.BLOCKED, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}
 
Example #29
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddStackTraceTimedWaiting() {
    System.out.println("add stacktrace : timed waiting");

    setState(stack0[0], Thread.State.TIMED_WAITING);

    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.TIMED_WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}
 
Example #30
Source File: StackTraceSnapshotBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddStackTraceWaiting() {
    System.out.println("add stacktrace : waiting");

    setState(stack0[0], Thread.State.WAITING);

    addStacktrace(stack0, 500000);

    assertEquals(500000, instance.currentDumpTimeStamp);
    assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState());
}