Thread state Analysis for Java language definitions

Source: Internet
Author: User
Tags thread class visualvm

When it comes to threading, be sure to talk about the thread state, the different states indicate that the thread is under different working mechanisms, and some actions may have different effects on the thread under different working mechanisms.

The Java language defines the state in 6, and at the same time, the thread has and only one of these States. To get the state of a Java thread you can use the GetState () method defined in the Java.lang.Thread class to get the state of the current thread using Thread.CurrentThread (). getState (). The type returned by the method is an enumeration type, which is an enumeration inside the thread, all called "java.lang.Thread.State", and the list of types defined in this enumeration is the thread state list for the Java language level, which contains the new, RUNNABLE, BLOCKED, waiting, timed_waiting, terminated these Values.

The following is the directory outline for this article:

A description of several thread states in Java

second, Java Thread state transition diagram

third, "VISUALVM Thread Monitoring thread state" and "java thread state" correspondence

A description of several thread states in Java

1. New (newly Created)

The new state description in the Java.lang.Thread.State enumeration:

/** * thread state for a thread which have not yet Started. */new

A thread that has not been started after creation is in this State.

This means that this thread is not started by start (), or is not really a thread at all, and essentially it just creates a Java shell that does not have a real thread to Run.

Does not mean that the call to start (), the state immediately changes, there are some steps in the middle, if there is another thread in this startup process to get its state, is actually uncertain, depends on whether those intermediate steps have been completed.

2, RUNNABLE (can be Run)

The runnable status description in the Java.lang.Thread.State enumeration:

/** * thread state for a runnable thread.  A thread in the runnable * The executing of the Java virtual machine but it could * be waiting for other resources from The operating system * such as Processor. */runnable

The runnable state includes running and ready in the operating system thread state, that is, a thread in this state may be running, or it may be waiting for system resources, such as waiting for the CPU to allocate time slices for it, such as waiting for network IO to read Data.

The runnable state can also be understood as surviving a thread that is trying to enlist the CPU (it is possible that the moment does not occupy the cpu, but it may be sending instructions waiting for the system to dispatch). Since in a real system, the CPU is only serving this thread after it is not opened, it must use many scheduling algorithms to achieve some kind of balance, but at this point the thread is still in the runnable State.

3, BLOCKED (blocking)

The Blocked status description in the Java.lang.Thread.State enumeration:

/** * thread state for 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 SYNCHR Onized Block/method after calling * {@link object#wait () object.wait}. * When a thread enters the synchronized statement block/method, if no lock is acquired, it becomes blocked * or is awakened by notify () after calling Object.wait (), and again into the synchronized statement block/method. If the lock is not acquired, it becomes BLOCKED */blocked

Blocked is called blocking state, or the thread has been suspended, it is "asleep", usually because it is waiting for a "lock", when attempting to enter a synchronized statement block/method, The lock is already occupied by other threads, it will be blocked, Until another thread has finished the critical section or the wait () operation of the corresponding lock object, it has the opportunity to compete for access to the critical Section.

In Java code, you need to consider the granularity of synchronized, or a thread that takes a lock for a long time, other threads that scramble for locks will block until the thread that owns the lock releases the lock

A thread in the blocked state cannot change its blocking state even if it calls Thread.Interrupt () because the interrupt () method simply sets the interrupt state of the thread, which is a token that does not wake the blocked thread

note: The Reentrantlock.lock () operation enters the waiting state, which internally calls the Locksupport.park () method

4, Waiting (wait Indefinitely)

/** * 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> * & Lt;li>{@link locksupport#park () locksupport.park}</li> * </ul> * * <p>a thread in the waiting state I s 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 * This Object. A thread that have called <tt>thread.join () </tt> * is waiting for a specified the thread to Terminate. */waiting

Threads in this state are not allocated CPU execution time, and they wait for the display to be awakened by other THREADS. This state is usually a result of invoking the wait () method operation of the corresponding lock object after a thread has an object lock and enters into the appropriate code Region. There are also Locksupport.park (), thread.join (), etc., which are also waiting for another event to occur, that is, to describe the meaning of the wait.

The following method causes the thread to fall into an indefinite wait state:

(1) object.wait () with timeout parameter not set

(2) thread.join () with timeout parameter not set

(3) Locksupport.park ()

Attention:

Locksupport.park (Object Blocker) suspends the current thread, and the parameter blocker is the "volatile Object Parkblocker member variable" that is used to set the current thread

Parkblocker is used to record which threads are blocked by who, and can be obtained through Locksupport.getblocker () to blocked objects for monitoring and analyzing threads.

The difference between "blocking" and "waiting":

(1) "blocking" state is waiting to acquire an exclusive lock, into the "blocking" state is passive, leaving the "blocking" state is because other threads release the lock, do not block;

(2) "wait" status is waiting for a period of time or wake-up action occurs, Enter the "wait" status is active

If the active call object.wait (), such as unable to get to reentraantlock, the active call Locksupport.park (), such as the main thread actively call Subthread.join (), so that the main thread waits for the child thread to complete before executing

The wait status is left because another thread has woken up or has reached the waiting time

5, timed_waiting (waiting for the Deadline)

/** * 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 positive waiting t Ime: * <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>{@link Locksupport#parknanos locksupport.parknanos}</li> *   <li>{@link LockSupport# Parkuntil locksupport.parkuntil}</li> * </ul> */timed_waiting

Threads in this state will not be allocated CPU execution time, But they will be automatically awakened by the system after a certain amount of time, without waiting for the wake to be displayed by other THREADS.

The following method causes the thread to enter the timed_waiting wait state:

(1) Thread.Sleep () method

(2) object.wait () method with timeout parameter set

(3) Thread.Join () method with timeout parameter set

(4) Locksupport.parknanos () method

(5) Locksupport.parkuntil () method

6, TERMINATED (end)

/** * Thread state for a terminated thread. * The thread has completed Execution. */terminated

The thread state of the thread has been terminated and the thread has finished Executing. In other words, the run () method is finished and the thread is in this State. In fact, this is just a state of the Java language level, the corresponding thread may have been unregistered within the operating system, or reused for other requests that need to use threads, while the Java language level is just the thread state seen through Java Code.

second, Java Thread state transition diagram

For individuals to understand the various situations of thread state transitions, if there is no place to welcome the exchange of Advice.

third, "VISUALVM Thread Monitoring thread state" and "java thread state" correspondence

When monitoring the JVM through visualvm, you can view the thread information of the JVM through the threads tab, VISUALVM the thread status as Follows:

Through the dump thread stack, and corresponding to the thread name in the VISUALVM monitoring information, find the VISUALVM thread stack for each thread state as Follows: (please focus on the Information)

1. operation

"http-bio-8080-acceptor-0" Daemon prio=6 tid=0x000000000d7b4800 nid=0xa264 runnable [0x000000001197e000]
Java.lang.Thread.State:RUNNABLE
At Java.net.DualStackPlainSocketImpl.accept0 (Native METHOD)
At Java.net.DualStackPlainSocketImpl.socketAccept (dualstackplainsocketimpl.java:131)
At Java.net.AbstractPlainSocketImpl.accept (abstractplainsocketimpl.java:398)
At Java.net.PlainSocketImpl.accept (plainsocketimpl.java:199)
-locked <0x00000000c2303850> (a Java.net.SocksSocketImpl)
At Java.net.ServerSocket.implAccept (serversocket.java:530)
At Java.net.ServerSocket.accept (serversocket.java:498)
At Org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket (defaultserversocketfactory.java:60)
At Org.apache.tomcat.util.net.jioendpoint$acceptor.run (jioendpoint.java:220)
At Java.lang.Thread.run (thread.java:745)

Locked ownable synchronizers:
-None

2, Sleep

"druid-connectionpool-destory-293325558" Daemon prio=6 tid=0x000000000d7ad000 nid=0x9c94 waiting on condition [0x000000000bf0f000]
Java.lang.Thread.State: timed_waiting (sleeping)
at Java.lang.Thread.sleep (Native METHOD)
At Com.alibaba.druid.pool.druiddatasource$destroyconnectionthread.run (druiddatasource.java:1685)

Locked ownable synchronizers:
-None

3. Wait

"Finalizer" Daemon prio=8 tid=0x0000000009349000 nid=0xa470 in object.wait ( ) [0x000000000a82f000]
      java.lang.Thread.State: waiting (on Object Monitor)
             at java .lang. Object.wait (Native METHOD)
           - waiting on <0x00000000c22a0108> (a Java.lang.ref.referencequeue$lock)
            at Java.lang.ref.ReferenceQueue.remove ( Referencequeue.java:135)

-locked <0x00000000c22a0108> (a Java.lang.ref.ReferenceQueue.Lock)
At Java.lang.ref.ReferenceQueue.remove (referencequeue.java:151)
At Java.lang.ref.finalizer$finalizerthread.run (finalizer.java:209)

Locked ownable synchronizers:
-None

"JMX Server Connection timeout" daemon prio=6 tid=0x000000000e846000 NID=0XAB10 inobject.wait ()[0x00000000137df000]
Java.lang.Thread.State: timed_waiting (on Object Monitor)
at java.lang.Object.wait (Native METHOD)
-waiting on <0x00000000c55da3f0>(a [I)
At Com.sun.jmx.remote.internal.servercommunicatoradmin$timeout.run (servercommunicatoradmin.java:168)
-locked <0x00000000c55da3f0> (a [I)
At Java.lang.Thread.run (thread.java:745)

Locked ownable synchronizers:
-None

4. Resident

"http-bio-8080-exec-2" Daemon prio=6 tid=0x000000000d7b8000 nid=0x9264Waiting on condition[0x000000000ee4e000]
Java.lang.Thread.State: Waiting (parking)
at Sun.misc.Unsafe.park (Native METHOD)
-parking to wait for <0x00000000c5629bc8>(a Java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject)
At Java.util.concurrent.locks.LockSupport.park (locksupport.java:186)
At Java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject.await (abstractqueuedsynchronizer.java : 2043)
At Java.util.concurrent.LinkedBlockingQueue.take (linkedblockingqueue.java:442)
At Org.apache.tomcat.util.threads.TaskQueue.take (taskqueue.java:104)
At Org.apache.tomcat.util.threads.TaskQueue.take (taskqueue.java:32)
At Java.util.concurrent.ThreadPoolExecutor.getTask (threadpoolexecutor.java:1068)
At Java.util.concurrent.ThreadPoolExecutor.runWorker (threadpoolexecutor.java:1130)
At Java.util.concurrent.ThreadPoolExecutor.Worker.run (threadpoolexecutor.java:615)
At Org.apache.tomcat.util.threads.TaskThread.WrappingRunnable.run (taskthread.java:61)
At Java.lang.Thread.run (thread.java:745)

Locked ownable synchronizers:
-None


"pool-9-thread-1" prio=6 tid=0x000000000d7b2000 NID=0XD5FCWaiting on condition[0x000000001187e000]
Java.lang.Thread.State: timed_waiting (parking)
at Sun.misc.Unsafe.park (Native METHOD)
-parking to wait for <0x00000000c563b9e0>(a Java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject)
At Java.util.concurrent.locks.LockSupport.parkNanos (locksupport.java:226)
At Java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject.awaitNanos ( Abstractqueuedsynchronizer.java:2082)
At Java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue.take (scheduledthreadpoolexecutor.java:1090 )
At Java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue.take (scheduledthreadpoolexecutor.java:807)
At Java.util.concurrent.ThreadPoolExecutor.getTask (threadpoolexecutor.java:1068)
At Java.util.concurrent.ThreadPoolExecutor.runWorker (threadpoolexecutor.java:1130)
At Java.util.concurrent.ThreadPoolExecutor.Worker.run (threadpoolexecutor.java:615)
At Java.lang.Thread.run (thread.java:745)

Locked ownable synchronizers:
-None

5. Monitoring

"Thread-1" prio=6 tid=0x000000000a8a1800 nid=0xfdb4 waiting for monitor entry [0x000000000b4de000]
Java.lang.Thread.State: BLOCKED (on Object Monitor)
At Com.jy.modules.test.test2$t.run (test2.java:58)
-waiting to lock <0x00000000eab757e0> (a Java.lang.Object)

Locked ownable synchronizers:
-None

The "VISUALVM thread monitoring thread state" corresponds to the "java thread state" relationship summary:

As can be seen, Visualvm's thread state will be "waiting" and "timed_waiting" two states according to the reason of the travel state is refined (in fact, Java thread stack dump has been refined)

The cause of the "timed_waiting" status may be:

Thread.Sleep ()--hibernation

Object.wait (timeout)--wait

Locksupport.parkuntil (deadline)--resident

Resources:

"in-depth understanding of Java Virtual machines"

"java commando" 5.1 Basic Introduction

Thread state Analysis for Java language definitions

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.