Sunday, December 8, 2013

The Lifecycle of a Thread in Java

Understanding the lifecycle of threads is very important while programming in Threads.

A Thread can be various states during its life time. The following diagram describes all the states a thread can undergo and the method calls that cause the transition from one state to another:


Java Thread States
  1. Runnable: A Thread starts its life from this state. Thread first enters into this state after the start() method of the thread is invoked. In this state, thread will be waiting for the scheduler to pick the thread for execution. The scheduler picks the threads based on their priorities. A thread can also re-enter this state either after running, waiting, sleeping or also while coming back from blocked state.
  2. Running: A thread is in running state means its currently running. There are several ways for thread to go into Runnable state. But there is only one way to come into Running state: the scheduler selects the thread for execution for the runnable pool. A thread runs until its swapped out, becomes blocked, or voluntarily give up its turn by invoking the static method Thread.yield().
  3. Dead: A thread enters this state when it completes execution. It may also enters this state when it is terminated by unrecoverable error condition. If a thread goes to this state means it can not be run again.
  4. Sleep: A Java thread may be forced to sleep (suspend) for some predefined time. In this state, thread is still alive but is not runnable, it might be return to runnable state later. It can throw InterruptedException.
  5. Blocked: A thread can enter blocked state because of waiting for the resources that are held by another thread.
    1. Blocked on I/O: Thread enters this state because of waiting for I/O resources. In this case, the thread will be sent back to Runnable state after the availability of resources.
    2. Blocked on Synchronization: Thread may enters this state while waiting for object lock. Thread will be moved to Runnable state after it acquires lock.
  6. Waiting state: A call to Object.wait() method causes the current object to wait. The thread remains in waiting state until some other thread invokes notify() or notifyAll() method of this object.

Release 5.0 introduced the Thread.getState() method, which results in one of the following Thread.State values:
  • NEW
  • RUNNABLE
  • BLOCKED
  • WAITING
  • TIMED_WAITING
  • TERMINATED
The Thread class API also introduced a method isAlive(), which returns true if the thread has already been started and not stopped. If the method isAlive() returns false, the thread is either New, or is Dead.

No comments:

Post a Comment