Java Multithreading Interview Questions and Answers 2024

Java Multithreading Interview Questions and Answers 2024

04 May 2024
151 Views
26 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Java Multithreading Interview Questions

Multithreading in Java stands out as a critical component for developers aiming to demonstrate their Java expertise. If Java is your preferred language for your software engineer interview, these Java Multithreading Interview Questions will give you an idea of the questions you will face in your interview. So don't miss out on this.

Our experts have crafted these interview questions based on a real-time analysis of the questions commonly asked in technical rounds today. The complexity of the questions is gradually moving from basic thread concepts to advanced concepts like context switching. It will help you build your concepts level by level. Still, if you think anything is left out, let us know in the comment section. 

Java Multithreading Interview Questions for Freshers

1. What is multithreading?

It is a process of executing multiple threads at the same time. Multithreading is used for multitasking purposes. It acquires less memory and provides fast and efficient performance. Multithreading's main advantages are as follows:

Here threads share the same address space.

  • lightweight thread.
  • The low cost of communication between the processes.

2. What is the thread?

A thread is nothing but a lightweight subprocess. It is a different path of execution. Each and every thread runs in a different-different stack frame. The process can contain multiple threads. Threads share usually the process resources, but still, they execute independently everytime.

3. Differentiate between process and thread.

  • A Program in the execution is called the process while A thread is a subset of the process.
  • Processes are independent while threads are the subset of process.
  • Processes have different address spaces in memory, on the other hand, threads contain a shared address space.
  • Context switching is much faster between the threads as compared to processes.
  • The change in the Parent process doesn't affect the child process while in the parent thread changes can affect the child thread.

Differentiate between process and thread.

4. What do you understand by inter-thread communication?

  • inter-thread communication is nothing but the process of communication between synchronized threads.
  • It is used to avoid thread polling in Java.
  • The thread is paused running in its critical section, and another thread is allowed to enter or it lock the same critical section to be executed.
  • inter-thread communication can be achieved by wait(), notify(), and notifyAll() methods.

5. What is the purpose of the wait() method in Java?

It is the method provided by the Object class in Java. It is used for inter-thread communication in Java. java. lang.Object. wait(), this method is used to pause the current thread and wait until another thread does not call the notify() or notifyAll() method. The syntax of the wait() method in javs is given below.

Syntax

 public final void wait()

6. Why must the wait() method be called from the synchronized block

We have to call the wait method otherwise it will throw java.lang.IllegalMonitorStateException type exception. Because of this, we need the wait() method for inter-thread communication with notify() and notifyAll() methods. Hence It must be present in the synchronized block for proper and correct communication.

7. What are the advantages of multithreading?

Multithreading programming has the following advantages:

  • It allows an application/program to be always reactive for input, even if already running with some background tasks
  • It allows the faster execution of tasks, as threads execute independently.
  • It provides better utilization of cache memory as threads share the common memory resources.
  • It reduces the number of the required server as one server can execute multiple threads at a time.

8. What are the states in the lifecycle of a Thread?

  • New: In this state, a Thread class object is created using a new operator, but the thread is not alive. The thread doesn't start until we call the start() method.
  • Runnable: In this state, the thread is run after calling the start() method. However, the thread is not yet selected by the thread scheduler.
  • Running: In this state, the thread scheduler picks the thread from the ready state.
  • And the thread is running.
  • Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the other thread to finish.
  • Dead/Terminated: A thread is in terminated or dead state when the run() method exits.

What are the states in the lifecycle of a Thread?

9. Explain the difference between preemptive scheduling and time slicing.

If we talk about preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. On the other hand, time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. Then the scheduler determines which task should execute next, based on priority and other factors.

10. What is context switching?

It is the state of the process (or thread) is stored so that it can be restored. The execution can be resumed from the same point after that. Context switching provides multiple processes to share the same CPU.

11. Differentiate between the Thread class and Runnable interface for creating a Thread.

  • The thread can be created by extending the Thread class
  • The thread can be created by implementing the Runnable interface

However, the primary differences between both ways are given below:

  • By extending the Thread class, you cannot extend any other class. Because Java does not allow multiple inheritances while implementing the Runnable interface; you can also extend other base classes if it is required.
  • By extending the Thread class, each thread creates a unique object. It is associated with it while implementing the Runnable interface. The multiple threads share the same object
  • The Thread class has various inbuilt methods like getPriority(), isAlive(), and many more while the Runnable interface has a single method, i.e., run().

12. What does join() method?

This method waits for a thread to die. It occurred the currently running threads to stop executing until the thread it joins with completes its task. The join() method is overloaded in the Thread class in the following ways.

  • The public void join() method throws InterruptedException.
  • The public void join(long milliseconds) method throws InterruptedException.

13. Describe the purpose and working of the sleep() method.

  • This method in Java is used to block a thread for a particular time, which means it pauses the execution of a thread for a specific time. There are two methods.
  • When you call the sleep() method, it pauses the execution of the current thread for the given amount of time and it gives priority to another thread if the thread is available.
  • When the waiting time is completed the again previous thread changes its state from waiting to runnable and comes into running state, and the whole process works so on till the execution is complete.

14.What is the difference between wait() and sleep() method?

15.Can we call the run() method instead of start()?

  • Yes, calling the run() method directly is valid, but it will not work as a thread instead it will work as a normal object. 
  • There is no context-switching between the threads. 
  • When we call the start() method, it internally calls the run() method. It creates a new stack for a thread while directly calling the run() will not create a new stack.

16. What about the daemon threads?

  • The daemon threads are the low-priority threads that provide the background support and services to the user threads.
  • Daemon thread gets automatically terminated by the JVM if the program remains with the daemon thread only, and all other user threads are ended/died. 
  • There are two methods for daemon thread available in the Thread class:
  • public void setDaemon(boolean status): It is used to mark the thread daemon thread or a user thread.
  • public boolean daemon (): It checks whether the thread is a daemon or not.

17. What are the two ways of implementing thread in Java?

There are basically two ways of implementing thread in Java as given below:

1. Extending the Thread class

Example


class MultithreadingDemo extends Thread 
{   
  public void run() 
 {   
     System.out.println("Welcome to Scholarhat.");    
 } 
  public static void main(String args[]) 
 {   
    MultithreadingDemo obj=new MultithreadingDemo();  
        obj.start();  
  }  
} 
    

Output

Welcome to Scholarhat.   

2. Implementing Runnable interface in Java

Example


class MultithreadingDemo implements Runnable 
{  
   public void run() 
 {  
      System.out.println("Welcome to Scholarhat..");  
  }  
    public static void main(String args[]) 
 {  
      MultithreadingDemo obj=new MultithreadingDemo();   
      Threadtobj =new Thread(obj);       tobj.start();  
 }   
} 
    

Output

Welcome to Scholarhat.   

18.What’s the difference between notify() and notifyAll()?

1.notify():

  • It sends a notification and wakes up only a single thread instead of multiple threads that are waiting on the object’s monitor.
  • The notify() method is defined in the Object class, which is Java’s top-level class.
  • It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution.
  • The thread class notify() method is used to wake up a single thread.

notify():

2.notifyAll():

  • It sends notifications wakes up all threads and allows them to compete for the object's monitor instead of a single thread.
  • The notifyAll() wakes up all threads that are waiting on this object’s monitor.
  • A thread waits on an object’s monitor by calling one of the wait methods.
  • The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.

notifyAll()

19. What do you understand about a “thread” in Java programming?

A “thread is the smallest unit of processing and is a lightweight subprocess executed independently. Each thread in the program runs on a different stack frame, and multiple threads form the complete program.

20. What are some fundamental advantages of multithreading in Java?

The key benefits of Java multithreading include:

  • Multiple threads can share single address spaces.
  • Threads share the same resources from the library but can execute differently.
  • Different threads can be made to perform various functions to yield a given result.

What are some fundamental advantages of multithreading in Java?

21. What is the fundamental difference between a process and a thread?

A process is part of the main program, while threads are subsets of processes. Processes have different address spaces in the memory, while threads share the same address space.

22. What is inter-thread communication?

Communication between synchronized threads is referred to as inter-thread communication. It is a core feature that helps to avoid thread-polling in Java. A particular thread can be paused through inter-thread communication to allow another thread to enter the block.

23. What are some functions used to perform inter-thread communication in Java?

This is one of the most common Java Multithreading interview questions asked in tech interviews. Some common functions used to perform inter-thread communication in Java are - notify(), wait(), and notifyAll().

24. What do you understand about the wait() function in Java?

The wait() function, specified by the object class, is used to pause the current thread and wait until another thread calls the notify() function. Note that the wait() method needs to be called from a synchronized block to avoid an exception from occurring.

25. What do you understand by context switching?

Context switching is a feature through which the current state of a thread is saved for it to be restored and executed later. Through context switching, multiple processes can share the same CPU.

26. What is the function of the join() method?

The join() method causes the current thread to stop running until the thread due congregates and completes its task. It is a commonly used function that facilitates the execution of multiple threads in an organized manner.

27. What is the function of the sleep() method?

This is yet another popular Java Multithreading Interview Question. The sleep() method is used to pause a particular thread from executing and prioritizes another thread that needs to be executed before the current thread executes.

28. What do you understand about Deadlock situations in Java Multithreading?

Deadlock is a situation where each thread is waiting for resources held by other waiting threads. Due to this situation, no threads are executed, causing a pause in program execution and breaking the code at runtime.

29. How do you detect deadlock situations in Java?

Deadlock situations can be detected by running the executable code on cmd and subsequently collecting the thread dump. If deadlock situations are present, the cmd will throw up a message.

30. How can deadlock situations be avoided in Java?

This is one of the most common Java Multithreading interview questions asked in technical interviews. Deadlock situations in Java can be avoided by:

  • By way of avoiding nested thread locks and providing locks to only one thread at a time
  • By using thread join - the function helps to wait for threads to execute before other threads are executed, thereby preventing multiple threads from waiting for resources used by other threads.

Java Multithreading interview questions for experienced

31. How do threads communicate with each other?

Threads can communicate using three methods i.e., wait(), notify(), and notifyAll().

32. Can two threads execute two methods (static and non-static concurrently)?

Yes, it is possible. If both the threads acquire locks on different objects, then they can execute concurrently without any problem.

33. What is the purpose of the finalize() method?

The finalize () method is basically a method of Object class specially used to perform cleanup operations on unmanaged resources just before garbage collection. It is not at all intended to be called a normal method. After the complete execution of the finalize() method, the object gets destroyed automatically.

34. What is the synchronized method and synchronized block? Which one should be preferred?

Synchronized Method: In this method, the thread acquires a lock on the object when they enter the synchronized method and releases the lock either normally or by throwing an exception when they leave the method. No other thread can use the whole method unless and until the current thread finishes its execution and release the lock. It can be used when one wants to lock on the entire functionality of a particular method.

35. What is Livelock? What happens when it occurs?

Similar to deadlock, livelock is also another concurrency problem. In this case, the state of threads changes between one another without making any progress. Threads are not blocked but their execution is stopped due to the unavailability of resources.

36. What is BlockingQueue?

  • BlockingQueue basically represents a queue that is thread-safe.
  • The producer thread inserts resource/element into the queue using put() method unless it gets full and consumer thread takes resources from the queue using take() method until it gets empty.
  • But if a thread tries to dequeue from an empty queue, then a particular thread will be blocked until some other thread inserts an item into the queue, or if a thread tries to insert an item into a queue that is already full, then a particular thread will be blocked until some threads take away an item from the queue.
  • Synchronized Block: In this method, the thread acquires a lock on the object between parentheses after the synchronized keyword, and releases the lock when they leave the block. No other thread can acquire a lock on the locked object unless and until the synchronized block exists. It can be used when one wants to keep other parts of the programs accessible to other threads.
  • Synchronized blocks should be preferred more as it boost the performance of a particular program. It only locks a certain part of the program (critical section) rather than the entire method and therefore leads to less contention.

Example



  package org.arpit.java2blog; 
 
import java.util.concurrent.ArrayBlockingQueue; 
import java.util.concurrent.BlockingQueue; 
 
public class BlockingQueuePCExample { 
 
   public static void main(String[] args) { 
 
       BlockingQueue queue=new ArrayBlockingQueue<>(5); 
       Producer producer=new Producer(queue); 
       Consumer consumer=new Consumer(queue); 
       Thread producerThread = new Thread(producer); 
       Thread consumerThread = new Thread(consumer); 
 
       producerThread.start(); 
       consumerThread.start(); 
 
   } 
 
   static class Producer implements Runnable { 
 
       BlockingQueue queue=null; 
 
       public Producer(BlockingQueue queue) { 
           super(); 
           this.queue = queue; 
       } 
 
       @Override 
       public void run() { 
 
               try { 
                   System.out.println("Producing element 1"); 
                   queue.put("Element 1"); 
                   Thread.sleep(1000); 
                   System.out.println("Producing element 2"); 
                   queue.put("Element 2"); 
                   Thread.sleep(1000); 
                   System.out.println("Producing element 3"); 
                   queue.put("Element 3"); 
               } catch (InterruptedException e) { 
 
                   e.printStackTrace(); 
               } 
       } 
   } 
 
   static class Consumer implements Runnable { 
 
       BlockingQueue queue=null; 
 
       public Consumer(BlockingQueue queue) { 
           super(); 
           this.queue = queue; 
       } 
 
       @Override 
       public void run() { 
 
           while(true) 
           { 
               try { 
                   System.out.println("Consumed "+queue.take()); 
               } catch (InterruptedException e) { 
                   e.printStackTrace(); 
               } 
           } 
       } 
 
   } 
} 
    

Output


Producing element 1 
Consumed Element 1 
Producing element 2 
Consumed Element 2 
Producing element 3 
Consumed Element 3
    

37. What is thread starvation?

Thread starvation is basically a situation or condition where a thread won’t be able to have regular access to shared resources and therefore is unable to proceed or make progress. This is because other threads have high priority and occupy the resources for too long. This usually happens with low-priority threads that do not get CPU for its execution to carry on.

38. Can you start a thread twice?

No, it's not at all possible to restart a thread once a thread gets started and completes its execution. Thread only runs once and if you try to run it for a second time, then it will throw a runtime exception i.e., java.lang.IllegalThreadStateException.

39. Explain context switching.

Context switching is basically an important feature of multithreading. It is referred to as switching of CPU from one thread or process to another one. It allows multiple processes to share the same CPU. In context switching, the state of thread or process is stored so that the execution of the thread can be resumed later if required.

40. What is CyclicBarrier and CountDownLatch?

  • CyclicBarrier and CountDownLatch, both are required for managing multithreaded programming. But there is some difference between them as given below:
  • CyclicBarrier: It is a tool to synchronize threads processing using some algorithm. It enables a set of threads to wait for each other till they reach a common execution point or common barrier points, and then let them further continue execution. One can reuse the same CyclicBarrier even if the barrier is broken by setting it.
  • CountDownLatch: It is a tool that enables main threads to wait until mandatory operations are performed and completed by other threads. In simple words, it makes sure that a thread waits until the execution in another thread completes before it starts its execution. One cannot reuse the same CountDownLatch once the count reaches 0.

41. What do you mean by inter-thread communication?

Inter-thread communication, as the name suggests, is a process or mechanism using which multiple threads can communicate with each other. It is especially used to avoid thread polling in java and can be obtained using wait(), notify(), and notifyAll() methods.

42. What is Thread Scheduler and Time Slicing?

Thread Scheduler: It is a component of JVM that is used to decide which thread will execute next if multiple threads are waiting to get the chance of execution. By looking at the priority assigned to each thread that is READY, the thread scheduler selects the next run to execute. To schedule the threads, it mainly uses two mechanisms: Preemptive Scheduling and Time slicing scheduling.

Time Slicing: It is especially used to divide CPU time and allocate them to active threads. In this, each thread will get a predefined slice of time to execute. When the time expires, a particular thread has to wait till other threads get their chances to use their time in a round-robin fashion. Every running thread will get executed for a fixed time period.

43. What is a shutdown hook?

A shutdown hook is simply a thread that is invoked implicitly before JVM shuts down. It is one of the most important features of JVM because it provides the capacity to do resource cleanup or save application state JVM shuts down. By calling the halt(int) method of the Runtime class, the shutdown hook can be stopped. Using the following method, one can add a shutdown hook.

44. What is busy spinning?

Busy Spinning, also known as Busy-waiting, is a technique in which one thread waits for some condition to happen, without calling wait or sleep methods and releasing the CPU. In this condition, one can pause a thread by making it run an empty loop for a certain time period, and it does not even give CPY control. Therefore, it is used to preserve CPU caches and avoid the cost of rebuilding cache.

45. What is ConcurrentHashMap and Hashtable? In java, why is ConcurrentHashMap considered faster than Hashtable?

  • ConcurrentHashMap: It was introduced in Java 1.5 to store data using multiple buckets. As the name suggests, it allows concurrent read and writes operations to the map. It only locks a certain portion of the map while doing iteration to provide thread safety so that other readers can still have access to the map without waiting for iteration to complete.
  • Hashtable: It is a thread-safe legacy class that was introduced in old versions of java to store key or value pairs using a hash table. It does not provide any lock-free read, unlike ConcurrentHashMap. It just locks the entire map while doing iteration.
  • ConcurrentHashMap and Hashtable, both are thread-safe but ConcurrentHashMap generally avoids read locks and improves performance, unlike Hashtable. ConcurrentHashMap also provides lock-free reads, unlike Hashtable. Therefore, ConcurrentHashMap is considered faster than Hashtable especially when the number of readers is more as compared to the number of writers.

46. Explain thread priority.

Thread priority simply means that threads with the highest priority will get a chance for execution prior to low-priority threads. One can specify the priority but it's not necessary that the highest priority thread will get executed before the lower-priority thread. Thread scheduler assigns processor to thread on the basis of thread priority. The range of priority changes between 1-10 from lowest priority to highest priority.

47. What do you mean by the ThreadLocal variable in Java?

ThreadLocal variables are special kinds of variables created and provided by the Java ThreadLocal class. These variables are only allowed to be read and written by the same thread. Two threads cannot be able to see each other’s ThreadLocal variable, so even if they will execute the same code, then there won't be any race condition and the code will be thread-safe.

48. What is semaphore?

Semaphore is regarded as a thread synchronization construct that is usually required to control and manage the access to the shared resource using counters. It simply sets the limit of the thread. The semaphore class is defined within the package java.util.concurrent and can be used to send signals between threads to avoid missed signals or to guard critical sections. It can also be used to implement resource pools or bounded collection.

49. Explain Thread Group. Why should we not use it?

ThreadGroup is a class that is used to create multiple groups of threads in a single object. This group of threads is present in the form of three structures in which every thread group has a parent except the initial thread. Thread groups can contain other thread groups also. A thread is only allowed to have access to information about its own thread group, not other thread groups.

50. What will happen if we don’t override the thread class run() method?

Nothing will happen as such if we don’t override the run() method. The compiler will not show any error. It will execute the run() method of thread class and we will just don’t get any output because the run() method is with an empty implementation.

Conclusion:
So, here we have covered the mostly asked Java Interview Questions from basic to advanced for all interested candidates. For a complete understanding of Java refer to our Java Certification Program.

FAQs

Q1. Is multithreading important in Java for an interview?

Multithreading allows the faster execution of tasks, as threads execute independently

Q2. Can we call run() method of a thread class?

The run() method is available in the thread class constructed using a separate Runnable object. 

Q3. Why multithreading is faster in Java?

Multithreading saves time as you can perform multiple operations together
Share Article
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this