article

Java Thread Interview Questions

3 min read

In this article series, we will discuss different types of questions that can be used in a Java interview, in order for the employer to test your skills in Java and object-oriented programming. This article is dedicated to Java Threads

Java Thread Interview Questions

What is the difference between processes and threads in Java?

Explain different ways of creating a thread. Which one would you prefer and why?

There are three ways that can be used in order for a Thread to be created:

The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritances, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.

Explain the available thread states in a high-level.

During its execution, a thread can reside in one of the following states:

What is the difference between a synchronized method and a synchronized block?

In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse-grained lock) or block level of code (fine-grained lock).

How does thread synchronization occur inside a monitor? What levels of synchronization can you apply?

The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock.

What’s a deadlock?

A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly.

How do you ensure that N threads can access N resources without deadlock?

A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise.

ALSO READ:
 General Java Interview Questions
Java Collections Interview Questions