Top 110 Java Multithreading Interview Questions and Answers (Part 2)

31. What is a Scheduler?
A scheduler is a program that is the implementation of a scheduling algorithm to manage access of processes and threads to limited resource like CPU or an I/O channel.
The goal of most scheduling algorithms is to provide load balancing for the available processes/threads and to guarantee that each process/thread will get a reasonable time frame to access the requested resource exclusively.

32. What is the minimum number of Threads in a Java program?
In a JVM, each Java program is executed within the main process that starts with java.exe. Therefore each Java application has at least one thread.

33. What are the properties of a Java thread?
Each Java thread has following properties:

  • 1. Identifier: An identifier of type long that is unique within the JVM
  • 2. Name: A name of type String
  • 3. Priority: Priority of type int
  • 4. State: A state of type java.lang.Thread.State
  • 5. Group: A thread group the thread belongs to

34. What are the different states of a Thread in Java?
Following are the different states of a Thread in Java:


  • 1. New: In the New state the thread has not yet.
  • 2. Runnable: A thread executing in the JVM is in Runnable state.
  • 3. Blocked: A thread waiting for a monitor lock is in Blocked state.
  • 4. Waiting: A thread waiting indefinitely for another thread to perform a particular action is in Waiting state.
  • 5. Timed_waiting: A thread waiting for another thread to perform an action for up to a specified waiting time is in Timed_waiting state.
  • 6. Terminated: A thread that has exited is in Terminated state.

35. How will you set the priority of a thread in Java?
The priority of a thread in Java can be set by using setPriority(int priority) method.
We can use constant Thread.MAX_PRIORITY to set the maximum priority of a thread.
We can use constant Thread.MIN_PRIORITY to set the minimum priority of a thread.
Or we can use constant Thread.NORM_PRIORITY to set the default priority of a thread.

36. What is the purpose of Thread Groups in Java?
In Java, every thread belongs to a group of threads.
The JDK class java.lang.ThreadGroup provides methods to handle a whole group of Threads.
With the help of these methods we can interrupt all threads of a group or set the maximum priority of all threads of a group.
So a thread group is used for taking collective actions on a group of threads.

37. Why we should not stop a thread by calling its stop() method?
The stop() method in Thread class is a deprecated method. Its use is not recommended.
When we call stop() method, the thread unlocks all monitors that it has acquired. If any locked object was in an inconsistent state, this state gets visible to all other threads.
It can cause unexpected behavior when other threads work on this inconsistent object.
So calling stop() method to stop a thread is not advisable.

38. How will you create a Thread in Java?
There are two main ways to create a thread in Java.

  • 1. Extend Thread class: We can extend java.lang.Thread class and implement run() method. On calling start()
    method it will start a new thread.
  • 2. Implement Runnable interface: We can implement java.lang.Runnable interface and pass the implemented
    object to the constructor of java.lang.Thread class. On calling start() it will start a new thread.

39. How can we stop a thread in the middle of execution in Java?
We can use a volatile variable as an indicator to stop the thread.
We can create a volatile reference pointing to the current thread.
This reference can be set to null by other threads to flag that the current thread should stop execution.
In following example threadStopper is the volatile reference that can be set as null in stopThread() method by other threads.
Sample code is as follows:

40. How do you access the current thread in a Java program?
We can access the current thread in Java by calling the static method currentThread() of java.lang.Thread class.
Sample code is as follows:

41. What is Busy waiting in Multithreading?
Busy waiting is also known as busy-looping or spinning. It is a multi-threading technique in which a process repeatedly checks if a condition is true.
For example, a process can keep checking if any keyboard input is available.
In general, busy waiting is considered as Anti-pattern that wastes processor time, so it should be avoided.
Sample code for busy waiting is as follows:

42. How can we prevent busy waiting in Java?
There is a simple way to prevent busy-waiting in Java. We can just put the current thread to sleep for given amount of time.
It can be done by calling sleep() method of java.lang.Thread class.
We can pass the number of milliseconds to sleep() method as an argument.

43. Can we use Thread.sleep() method for real-time processing in Java?
Java does not guarantee that Thread.sleep() will cause the thread to sleep for exactly N number of milliseconds. Sometime the thread can sleep for than N number of milliseconds.
In real-time processing we need precise time period for which a thread should run or sleep.
Therefore the invocation of Thread.sleep() method is not recommended for use in real-time processing.

44. Can we wake up a thread that has been put to sleep by using Thread.sleep() method?
We can use interrupt() method of java.lang.Thread class to interrupt a thread that is in sleep state. It will get InterruptedException to wake up from the sleep.
Sample code is as follows:

45. What are the two ways to check if a Thread has been interrupted?
These are the two ways to check for thread interruption:

  • 1. In Java, a Thread can call Thread.interrupted() method to check if it has been interrupted or not.
  • 2. The other option is to call isInterrupted() method of Thread class to check if it has been interrupted or not.

46.How can we make sure that Parent thread waits for termination of Child thread?
We can use join() method for this purpose. On calling join() method, current thread waits for the child thread to which it joins to finish.
Sample code is as follows:

47. How will you handle InterruptedException in Java?
In Java we can get InterruptedException from sleep() or join() methods. Throwing InterruptedException is way to inform that another thread has interrupted this thread.
In general, the purpose of Interrupt is to ask current thread to stop its current execution and finish unexpectedly.
Therefore ignoring this exception by catching it and only logging it to the console or some log file is not the recommended approach.
The run() method of the Runnable interface does not allow that throwing any exceptions. So we cannot re-throw InterruptedException.
Therefore the correct way to handle this exception is that run() method should check and handle this exception by itself and take appropriate action.

48. Which intrinsic lock is acquired by a synchronized method in Java?
When we mark a method as synchronized and then call this method, then this method will first acquire the intrinsic lock of the object in which that method is mentioned.
Once the synchronized method returns, it releases the lock.
In case the synchronized method throws an exception, the intrinsic lock will be released.
Sample code equivalent to a synchronized method is:

49. Can we mark a constructor as synchronized in Java?
No. We cannot mark a constructor as synchronized.
This will lead to compiler error.
The reasoning behind this is that, in this case, only the constructing thread would have access to the object being constructed.
50. Can we use primitive values for intrinsic locks?
No. Java does not allow primitive values to be used for intrinsic locks.

51. Do we have re-entrant property in intrinsic locks?
Yes. An intrinsic lock can be accessed by the same thread multiple times. So an Intrinsic lock is re-entrant.
If it is not allowed then the code that acquires a lock would have to avoid acquiring the lock that it has already acquired.

52. What is an atomic operation?
An atomic operation is an operation that completes in a single step relative to other threads.
An Atomic operation is either executed completely or not at all.
There is no halfway mark in Atomic operation.
53. Can we consider the statement i++ as an atomic operation in Java?
No. The statement i++ is not an Atomic operation. It has more than one operation.
First JVM loads the current value of i in memory. Then it increments it. Finally it stores the new value back into variable i.
The current thread that executes this operation may be interrupted between any of the above-mentioned three steps. Therefore it is not an atomic operation.
54. What are the Atomic operations in Java?
Java language provides some basic Atomic operations. These operations can be used to make sure that concurrent threads always see the same value.
Some of these Atomic operations are:

  • 1. Read operations on reference variables and primitive variables (except long and double)
  • 2. Write operations on reference variables and primitive variables (except long and double)
  • 3. Read operations on all variables declared as volatile
  • 4. Write operations on all variables declared as volatile

55. Can you check if following code is thread-safe?

The above-mentioned code is for creating a Singleton class. But this code is not thread-safe.
In this we check the value of instance second time in the synchronized block. But the JIT compiler can rearrange the Bytecode in such a way that the reference to SingletonDoubleCheck instance will be set before the execution of constructor.
Due to this the method getInstance() will return an object that may not have been initialized properly.
We can use the keyword volatile for instance to make this threadsafe code.
Any variables that is marked as volatile will be visible to other threads only after the completion of the constructor of the object.

56.What are the minimum requirements for a Deadlock situation in a program?
For a deadlock to occur following are the minimum requirements:


  • 1. Mutual exclusion: There has to be a resource that can be accessed by only one thread at any point of time.
  • 2. Resource holding: One thread locks one resource and holds it, and at the same time it tries to acquire lock on another mutually exclusive resource.
  • 3. No preemption: There is no pre-emption mechanism by which resource held by a thread can be freed after a specific period of time.
  • 4. Circular wait: There can be a scenario in which two or more threads lock one resource each and they wait for each other’s resource to get free. This causes circular wait among threads for same set of resources.

57. How can we prevent a Deadlock?
To prevent a Deadlock from occurring at least one requirement for a deadlock has to be removed:

  • 1. Mutual exclusion: We can use optimistic locking to prevent mutual exclusion among resources.
  • 2. Resource holding: A thread has to release all its exclusive locks if it does not succeed in acquiring all exclusive locks for resources required.
  • 3. No preemption: We can use timeout period for an exclusive lock to get free after a given amount of time.
  • 4. Circular wait: We can check and ensure that circular wait does not occur, when all exclusive locks have been acquired by all the threads in the same sequence.

58. How can we detect a Deadlock situation?
We can use ThreadMXBean.findDeadlockedThreads() method to
detect deadlocks in Java program. This bean comes with JDK:
Sample code is as follows:

59. What is a Livelock?
Livelock is a scenario in which two or more block each other by responding to an action caused by another thread.
In a deadlock situation two or more threads wait in one specific state.
In a Livelock scenario, two more threads change their state in such a way that it prevents progress on their regular work.
E.g. Consider scenario in which two threads try to acquire two
locks. They release a lock that they have acquired, when they cannot acquire the second lock.
In a Livelock situation, both threads concurrently try to acquire the locks. Only one thread would succeed, the second thread may succeed in acquiring the second lock.
Now both threads hold two different locks. And both threads want to have both locks. So they release their lock and try again from the beginning. This situation keeps repeating multiple times.

60. What is Thread starvation?
In a priority based scheduling, Threads with lower priority get lesser time for execution than higher priority threads.
If a lower priority thread performs a long running computation, it may happen that this thread does not get enough time to finish its computations just in time. In such a scenario, the tread with lower priority would starve. It will remain away from the threads with higher priority.

Continue to reading the 110 Java Multithreading Interview Questions and Answers (Part 3)





Leave a Comment


Please share it if you found this useful
Hide Buttons