{{announcement.body}}
{{announcement.title}}

Interview-Ready Snippets of Code for Thread Life Cycle States

DZone 's Guide to

Interview-Ready Snippets of Code for Thread Life Cycle States

Almost any Java technical interview contains several questions covering Java concurrency topics — here are some examples to help you prepare!

· Performance Zone ·
Free Resource

interview

Read on to find out some Java technical interview questions!

Almost any Java technical interview contains several questions covering Java concurrency topics. A common scenario for a beginner-intermediate level sound like this:

Interviewer: Can you enumerate the Java thread life cycle states?

Candidate: Yes, sure! So, we have: NEW , RUNNABLE , BLOCKED , WAITING , TIMED_WAITING , and TERMINATED .

Interviewer: Ok! Now, can you write a snippet of code that reveals the BLOCKED state?

Well, let's see how we can write snippets of codes for each state.

You may also like: How to Read a Thread Dump

The states of a Java thread are expressed via the Thread.State enumeration. The possible states of a Java thread are shown in the following diagram:

The different lifecycle states are as follows:

  • The NEW state.
  • The RUNNABLE state.
  • The BLOCKED state.
  • The WAITING state.
  • The TIMED_WAITING state.
  • The TERMINATED state.

Let's learn about all the different states in the following sections.

The NEW State

A Java thread is in the NEW state if it is created but not started (the thread constructor creates threads in the NEW state). This is its state until the start() method is invoked. The code bundled with this article contains several snippets of code that reveal this state via different construction techniques, including lambdas. For brevity, the following is just one of these constructions:

Java


The RUNNABLE State

The transition from NEW to RUNNABLE is obtained by calling the start() method. In this state, a thread can be running or ready to run. When it is ready to run, a thread is waiting for the JVM thread-scheduler to allocate the needed resources and time to run to it.

As soon as the processor is available, the thread-scheduler will run the thread. The following snippet of code should print RUNNABLE , since we print the state of the thread after calling start() . But because of thread-scheduler internal mechanisms, this is not guaranteed (interviewers love this kind of hints):

Java


The BLOCKED state

When a thread is trying to execute I/O tasks or synchronized blocks, it may enter into the BLOCKED state. For example, if a thread, t1 , tries to enter into a synchronized block of code that is already being accessed by another thread, t2 , then t1 is kept in the BLOCKED state until it can acquire the lock.

This scenario is shaped in the following snippet of code:

1. Create two threads: t1 and t2 .

2. Start t1 via the start() method:

         1. t1 will execute the run() method and will acquire the lock for the synchronized                                        method,syncMethod() .

         2. The syncMethod() will keep t1 inside forever, since it has an infinite loop.

3. After two seconds (arbitrary time), start t2 via the start() method:

         1. t2 will execute the run() code and will end up in the BLOCKED state since it cannot acquire 

               the lock of syncMethod() .

The code snippet is as follows:

Java


Here is a possible output (the names of threads may differ from here):

Java




xxxxxxxxxx
1


 
1
Thread Thread-0 is in run() method
2
Thread Thread-0 is in syncMethod() method
3
Thread Thread-1 is in run() method
4
BlockedThread t1: RUNNABLE(Thread-0)
5
BlockedThread t2: BLOCKED(Thread-1)



The WAITING State

A thread, t1 , that waits (without a timeout period) for another thread, t2 , to finish is in the WAITING state. This scenario is shaped in the following snippet of code:

1. Create a thread: t1.

2. Start t1 via the start() method.

3. In the run() method of t1:

            1. Create another thread: t2.

            2. Start t2 via the start() method.

            3. While t2 is running, call t2.join() — since t2 needs to join t1 (or, in other words, t1

       needs to wait for t2 to die), t1 is in the WAITING state.

4. In the run() method of t2 , t2 prints the state of t1 , which should be WAITING (while printing the t1 state, t2 is running, therefore t1 is waiting).

The code snippet is as follows:

Java


The TIMED_WAITING State

A thread, t1, that waits for an explicit period of time for another thread, t2, to finish is in the TIMED_WAITING state. This scenario is shaped in the following snippet of code:

1. Create a thread: t1.

2. Start t1 via the start() method.

3. In the run() method of t1, add a sleep time of two seconds (arbitrary time).

4. While t1 is running, the main thread prints the t1 state — the state should be TIMED_WAITING since t1 is in a sleep() that will expire after two seconds.

The code snippet is as follows:

Java


The TERMINATED State

A thread that successfully finishes its job or is abnormally interrupted is in the TERMINATE state. This is very simple to simulate, as in the following snippet of code (the main thread of the application prints the state of the thread, t — when this is happening, the thread, t, has done its job):

Java


Done! Commonly, the last question of an interviewer about Java concurrency topic will sound like this: In order to write thread-safe classes, what techniques do you consider? Well, a possible answer will mention the following techniques:

  • Have no state (classes with no instance and static variables).
  • Have state, but don't share it (for example, use instance variables via Runnable, ThreadLocal, and so on).
  • Have state, but an immutable state.
  • Use message-passing (for example, as Akka framework).
  • Use synchronized blocks.
  • Use volatile variables.
  • Use data structures from the java.util.concurrent package.
  • Use synchronizers (for example, CountDownLatch and Barrier).
  • Use locks from the java.util.concurrent.locks package.

The complete code is available on GitHub.

If you enjoyed this article, then you'll love my book, Java Coding Problems, that contains a dedicated chapter including 27 problems dedicated to Java concurrency topic.


Further Reading

The Evolution of the Producer-Consumer Problem in Java

Why Is Combining Thread-Safe Methods an Error?

Spring Bean Lifecycle

Topics:
java ,concurrency ,thread ,performance ,interview ,thread life

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}