Learn Java thread State and understand thread information in thread dump file

Source: Internet
Author: User
Tags mixed

The state of the thread is a very important thing, so the threads dump will show these states, through the analysis of these states, can get the health of the thread, and then discover possible problems. The state of the thread is defined in the Thread.state enumeration type:

 Public enum State {/** * thread ' state ' for a thread which have not yet started.  */NEW,/** * thread state for a runnable thread. A thread in the runnable * was executing in the Java Vsan but it could be waiting for othe         R resources from the operating system * such as processor.         */RUNNABLE,/** * thread state-a thread blocked waiting for a monitor lock.  * A thread in the blocked state was waiting for a monitor lock * to enter A synchronized Block/method or *         Reenter a synchronized block/method after calling * {@link object#wait () object.wait}.         */BLOCKED,/** * thread state for a waiting thread.   * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link object#wait () object.wait} with no timeout</li> * <li>{@link #join () Thread.Join} with no timeout</li> * <li>{@link Locksup  Port#park () locksupport.park}</li> * </ul> * * <p>a thread in the waiting state           Is waiting for another the thread to * perform a particular action.  * For example, a thread of that have called <tt>object.wait () </tt> * on an Object are waiting for          Another thread to call * <tt>object.notify () </tt> or <tt>object.notifyall () </tt> on * that object.         A thread that have called <tt>thread.join () </tt> * is waiting for a specified the thread to terminate.         */Waiting,/** * thread state is a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with A specified POS     Itive Waiting time: * <ul>    * <li>{@link #sleep thread.sleep}</li> * <li>{@link object#wait (Long) object.wait} with timeout</li> * <li>{@link #join (Long) Thread.Join} with timeout</li> * <li>{@l Ink Locksupport#parknanos locksupport.parknanos}</li> * <li>{@link locksupport#parkuntil LockSuppor t.parkuntil}</li> * </ul> * * timed_waiting,/** * Thread State for a ter         minated thread.         * The thread has completed execution. */TERMINATED;}

Below is a brief description of these status values:

1. NEW:

we know that each thread has a corresponding thread object in the heap memory. Thread t = new thread (), and when you have just created a thread object in heap memory, it is in the new state before the T.start () method is called. In this state, there is no difference between a thread and a normal Java object, just a pair of images in a heap memory .

2, RUNNABLE

This state indicates that the thread has all the running conditions, prepares the operating system for scheduling in the running queue, or is running. This state of the thread is normal, but if the thread stays in this state for a long time, it is unhealthy, indicating that the thread has been running for a long time (there is a performance problem), or that the thread has not been able to execute (there is a problem with thread starvation).

3, BLOCKED

The thread is waiting to get the monitor of the Java object (also called the built-in lock), that is, the thread is waiting to enter a method or block of code protected by synchronized. synchronized is used to guarantee atomicity, at most one thread can enter the critical region at any time, and other threads can only wait in line.

4, waiting

In the state of the thread, waiting for an event to occur, and only certain conditions are met to get an opportunity to execute. This particular event is usually the result of another thread. That is, if a particular event does not occur, the thread in that State waits for the opportunity to execute. For example, a thread invokes the Obj.wait () method of the Obj object, and if no thread calls obj.notify or Obj.notifyall, then a thread has no way to resume running If a thread calls Locksupport.park () and no other thread calls Locksupport.unpark (a), then a has no way to resume running.

5. timed_waiting

We know that there are many thread-related classes in J.U.C, which provide both time-limited and unlimited versions of APIs. timed_waiting means that threads invoke a timed version of the API and are waiting for the time to elapse, and when the wait time passes, the thread can resume running. If a thread enters the waiting state, it must be a specific event to be resumed, while the thread in Timed_waiting will resume running if a particular event occurs or the time elapses.

6, TERMINATED

The thread will be stuck in this state when it finishes executing, when the Run method returns normally, or throws a run-time exception. At this point the thread is left with only thread objects.



Next we use the Jstack tool provided by the JDK to see the status of the threads in the thread dump file. The 3 states of NEW, RUNNABLE, andterminated are easy to understand, and are mainly about 3 other states.

1. Display blocked status

Package Jstack;public class Blockedstate{private static Object object = new Object ();p ublic static void Main (string[] args {Runnable task = new Runnable () {@Overridepublic void run () {synchronized (object) {Long begin = System.currenttimemillis ( ), Long end = System.currenttimemillis (),//Allow thread to run for 5 minutes, will hold object's monitor while ((End-begin) <= 5 * *) {}}}};new thre AD (Task, "T1"). Start (); New Thread (Task, "T2"). Start ();}}
The thread that gets the object first executes 5 minutes, which will hold the monitor of object for 5 minutes, and the other thread cannot execute in the blocked State

< Span style= "font-size:18px" >

C:\ Documents and settings\administrator>jps5400 Jps33644752 blockedstatec:\documents and settings\administrator> Jstack 47522014-09-23 19:42:28full thread dump Java HotSpot (TM) Server VM (20.12-b01 mixed mode): "DESTROYJAVAVM" Prio=6 ti D=0X00856C00 nid=0x1314 waiting on condition [0x00000000] Java.lang.Thread.State:RUNNABLE "T2" prio=6 tid=0x27d7a800 nid =0X1350 Waiting for monitor entry [0x2833f000] Java.lang.Thread.State:BLOCKED (on object monitor) at Jstack. Blockedstate$1.run (blockedstate.java:17)-Waiting to lock <0x1cfcdc00> (a java.lang.Object) at JAVA.L Ang. Thread.run (thread.java:662) "T1" prio=6 tid=0x27d79400 nid=0x1338 runnable [0x282ef000] Java.lang.Thread.State: RUNNABLE at Jstack. Blockedstate$1.run (blockedstate.java:22)-Locked <0x1cfcdc00> (a java.lang.Object) at Java.lang.Threa D.run (thread.java:662) 
with thread dump you can see that the T2 thread is indeed in blocked (on object monitor). Waiting for monitor entry waiting to enter the synchronized protected area.


2. Display waiting status

Package Jstack;public class Waitingstate{private static Object object = new Object ();p ublic static void Main (string[] args {Runnable task = new Runnable () {@Overridepublic void run () {synchronized (object) {Long begin = System.currenttimemillis ( ), Long end = System.currenttimemillis (),//allow the thread to run for 5 minutes, will always hold the object's monitor while ((End-begin) <= 5 * *) {try{//Enter the same , the release monitor object.wait () is entered. catch (Interruptedexception e) {e.printstacktrace ();}}}}; New Thread (Task, "T1"). Start (); New Thread (Task, "T2"). Start ();}}
C:\Documents and settings\administrator>jps3356 Jps33645784 waitingstatec:\documents and Settings\Administrator >jstack 57842014-09-23 19:48:43full thread dump Java HotSpot (TM) Server VM (20.12-b01 mixed mode): "DESTROYJAVAVM" prio=  6 tid=0x00856c00 nid=0x1734 waiting on condition [0x00000000] Java.lang.Thread.State:RUNNABLE "T2" prio=6 tid=0x27d7e000 Nid=0x17f4 in Object.wait () [0x2833f000] Java.lang.Thread.State:WAITING (on Object monitor) at Java.lang.Object . Wait (Native Method)-Waiting on <0x1cfcdc00> (a java.lang.Object) at Java.lang.Object.wait (Object.ja va:485) at Jstack. Waitingstate$1.run (waitingstate.java:26)-Locked <0x1cfcdc00> (a java.lang.Object) at Java.lang.Threa D.run (thread.java:662) "T1" prio=6 tid=0x27d7d400 nid=0x17f0 in object.wait () [0x282ef000] Java.lang.Thread.State: Waiting (on object monitor) at java.lang.Object.wait (Native Method)-Waiting on <0x1cfcdc00> (a java. Lang. Object)       At Java.lang.Object.wait (object.java:485) at Jstack. Waitingstate$1.run (waitingstate.java:26)-Locked <0x1cfcdc00> (a java.lang.Object) at Java.lang.Threa D.run (thread.java:662)
you can see that both T1 and T2 are in the waiting (on object monitor), and the reason for entering the wait state is to call in Object.wait (). Through the J.U.C package under the lock and condition queue, but also this effect, we can practice under their own.

3. Display timed_waiting status

package Jstack;import Java.util.concurrent.timeunit;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class TimedWaitingState{// Java display lock, similar to Java object built-in monitor private static lock lock = new Reentrantlock ();//Lock associated conditional queue (similar to object.wait) private static Condition Condition = lock.newcondition ();p ublic static void Main (string[] args) {Runnable task = new Runnable () {@Override public void Run () {//locking, enters critical section lock.lock (); try{condition.await (5, timeunit.minutes);} catch (Interruptedexception e) { E.printstacktrace ();} Unlock, Exit critical section Lock.unlock ();}}; New Thread (Task, "T1"). Start (); New Thread (Task, "T2"). Start ();}} 
C:\Documents and settings\administrator>jps5952 Jps33645732 timedwaitingstatec:\documents and Settings\ Administrator>jstack 57322014-09-23 19:59:44full thread dump Java HotSpot (TM) Server VM (20.12-b01 mixed mode): "Destro YJAVAVM "Prio=6 tid=0x00856c00 nid=0x169c waiting on condition [0x00000000] Java.lang.Thread.State:RUNNABLE" T2 "prio=6 tid=0x27d7d800 nid=0xc30 waiting on condition [0x2833f000] Java.lang.Thread.State:TIMED_WAITING (parking) at Sun . misc. Unsafe.park (Native Method)-Parking to wait for <0x1cfce5b8> (a java.util.concurrent.locks.AbstractQueuedSy Nchronizer$conditionobject) at Java.util.concurrent.locks.LockSupport.parkNanos (locksupport.java:196) at JAV        A.util.concurrent.locks.abstractqueuedsynchronizer$conditionobject.await (abstractqueuedsynchronizer.java:2116) At Jstack. Timedwaitingstate$1.run (timedwaitingstate.java:28) at Java.lang.Thread.run (thread.java:662) "T1" Prio=6 tid=0x280d0 C00 nid=0x16e0 waiting on condition [0x282ef000] Java.lang.Thread.State:TIMED_WAITING (parking) at Sun.misc.Unsafe.park (Native Method)        -Parking to wait for <0x1cfce5b8> (a java.util.concurrent.locks.abstractqueuedsynchronizer$conditionobject) At Java.util.concurrent.locks.LockSupport.parkNanos (locksupport.java:196) at Java.util.concurrent.locks.AbstractQ Ueuedsynchronizer$conditionobject.await (abstractqueuedsynchronizer.java:2116) at Jstack. Timedwaitingstate$1.run (timedwaitingstate.java:28) at Java.lang.Thread.run (thread.java:662)
you can see that both the T1 and T2 threads are in Java.lang.Thread.State:TIMED_WAITING (parking), and this parking represents the tool class under the Juc of the call, not the Java default monitor. The difference between the built-in lock and the display lock, you can see me under the Java Concurrency related articles Java Concurrency programming topic http://blog.csdn.net/aitangyong/article/category/2298385



Next look at thread dump print out what the message means, the basic of each thread is the same, we randomly select one, analysis:

"T1" prio=6 tid=0x27d7d400 nid=0x17f0 in object.wait () [0x282ef000]   Java.lang.Thread.State:WAITING (on Object Monitor) at        java.lang.Object.wait (Native Method)        – Waiting on <0x1cfcdc00> (a java.lang.Object)        at Java.lang.Object.wait (object.java:485) at        Jstack. Waitingstate$1.run (waitingstate.java:26)        -locked <0x1cfcdc00> (a java.lang.Object)        at Java.lang.Thread.run (thread.java:662)
T1: This is the thread name, which can be specified at the time of the new thread () object, or call Thread.setname. With this name, it is more convenient to search for thread dump. This is why it is generally necessary to specify the thread name when creating the thread, rather than using the default name.

Prio=6: This represents the priority of the thread, or it can be modified by the API in the thread class. In practice, this property is generally not set and is not of much use.

The thread ID of the Tid:java (this thread is uniquely identified in the current virtual machine).

Nid: Thread-local identity, which is the identity of the thread in the operating system.

[0x282ef000]: The memory address of the object, through the JVM memory viewing tool, can see where the thread is waiting on the object.

Java.lang.Thread.State:WAITING (on object monitor): Shows the state of the current moment of the thread, and the reason why the parentheses are in that state.

At the bottom of the line is the thread's call stack, which lets you see the process by which the thread executes the code.


Finally we look at the difference between the waiting for monitor entry and in Object.wait () from the dump file . The first thing we need to note is that these 2 things are for the object's monitor, as long as the monitor is the same, because the monitor is built-in to the JVM, so it can be imagined that this monitor is specially handled within the JVM. The display lock lock does not differentiate between the 2 states after JDK5.0, because lock is an ordinary Java object for the JVM. The following diagram depicts the relationship between the thread and monitor, and the state transition diagram of the thread:


As you can see, each monitor can be owned by only one thread at a time, and the thread is "Active thread", while the other threads are "waiting thread", waiting in the two queue "Entry set" and "Wait set" respectively. The state of the thread waiting in "Entry set" is "Waiting for monitor Entry", while the thread state waiting in "wait set" is "in Object.wait ()". Simply understood:"Entry set" holds a thread waiting to enter synchronized, and"Wait set" holds a thread that has entered synchronized but called object.wait.




Learn Java thread State and understand thread information in thread dump file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.