Briefly Explain High-Level Thread States

The state chart diagram below describes the thread states.

 

Runnable: A thread becomes runnable when you call the start( ), but does  not necessarily start running immediately.  It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.

MyThread aThread = new MyThread();

aThread.start();                   //becomes runnable

Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokescurrObject.notify( ) or the currObject.notifyAll( ) is executed.

Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);

Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.

Blocked on synchronization: will move to running when a lock is acquired.

Dead: The thread is finished working.

Thread.State enumeration contains the possible states of a Java thread in the underlying JVM. These thread states are possible due to Java’s following thread concepts:

  • The objects can be shared and modified (i.e. if mutable) by any threads.
  • The preemptive nature of the thread scheduler can swap threads on and off cores in a multi-core CPU machine at any time.
  • This means the methods can be swapped out while they are running. Otherwise a method in an infinite loop will clog the CPU forever leaving the other methods on different threads to starve.
  • To prevent thread safety issues, the methods and block of code that has vulnerable data can be locked.
  • This enables the threads to be in locked or waiting to acquire a lock states.
  • The threads also get into the waiting state for I/O resources like sockets, file handles, and database connections.
  • The threads that are performing I/O read/write operations can not be swapped. Hence, they need to eithercomplete to the finished state with success/failure or another thread must close the socket for it to get to the state of dead or finished. This is why proper service timeout values are necessary to prevent the thread to get blocked for ever in an I/O operation, causing performance issues.
  • The threads can be put to sleep to give other threads in waiting state an opportunity to execute.