Java Multithreading Interview Questions and Answers 2024

Java Multithreading Interview Questions and Answers 2024

16 Jun 2024
775 Views
30 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.

Java Multithreading Interview Questions for Freshers

1. What is multithreading?

It is a process of concurrently executing multiple threads or parts of a program. Multithreading is used for multitasking purposes. It acquires less memory and provides fast and efficient performance.

2. What is the thread?

A thread is nothing but a lightweight subprocess. It is a different path of execution. Every thread runs in a different stack frame. The process can contain multiple threads. Every thread shares the same memory space.

3. Differentiate between process and thread.

Differentiate between process and thread.

ProcessThread
A program in execution is a processThread is a part of a process
Processes are heavyweightThreads are lightweight
Termination is slowTermination is fast
Creation takes timeCreation takes less time
Communication between processes needs more time Communication between threads requires less time
More time for context-switching Less time for context-switching
Processes do not share memoryThreads share memory
Consumes more resourcesConsumes lesser resources

4. What is 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 the same critical section to be executed.
  • inter-thread communication can be achieved by wait(), notify(), and notifyAll() methods.

5. Explain wait() method in Java? Why must it be called from the synchronized block?

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

Syntax

 public final void wait()

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.

6. How will you synchronize a method in Java?

We can use the synchronized modifier in the method's signature or use the synchronized {} construct inside the method.

Example


   public void swap()
   {
       synchronized (this)
       {
       //Code
       }
   }

   public synchronized void swap1EqualsSwap()
   {
   //Code
   }

   public static synchronized void swap2()
   {
   //Code
   }

   public static void swap3EqualsSwap2()
   {
       synchronized (JoinClass.class)
       {
           //Code
       }
   }

7. What are the advantages of multithreading?

  • Improved Performance: Multithreaded programs can use multi-core processors, making them faster and more efficient.
  • Enhanced Responsiveness: Multithreading allows for responsive user interfaces (UIs) in applications. Long-running tasks can be moved to background threads, ensuring the UI remains responsive to user input.
  • Resource Utilization: Multithreading enables better utilization of system resources, as different threads can execute different tasks simultaneously.
  • Parallel Processing: Multithreading is essential for parallel processing, where a large task is divided into smaller sub-tasks that can be executed concurrently, reducing overall execution time.

What are some fundamental advantages of multithreading in Java?

8. Discuss the states in the lifecycle of a Thread.

  • New: 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: The thread is run after calling the start() method. It is waiting in the ready or runnable queue to be allocated to the processor.
  • Running: In this state, the thread scheduler picks the thread from the ready state and the thread executes.
  • Waiting/Blocked: In this state, a thread is not running but still alive, or waiting for the other thread to finish.
  • Dead/Terminated: The thread exits or stops executing due to some unusual happenings.

What are the states in the lifecycle of a Thread?

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

In preemptive scheduling, the highest priority task executes until it enters the waiting or dead state or a higher priority task comes into existence. On the other hand, in 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?

Context Switching is the process/method used by the system to change the process from one state to another using the CPUs present in the system to perform its job. It allows a single CPU to handle multiple process requests parallelly without the need for any additional processors.

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
Thread ClassRunnable Interface
It has multiple methods like start() and run()It has only abstract method run()
Each thread creates a unique object and gets associated with itMultiple threads share the same objects
More memory required Less memory required
Multiple Inheritance is not allowed in Java hence after a class extends the Thread class, it can not extend any other classIf a class implements the runnable interface, it can extend another class.

12. What is join() method?

One thread can call the join() method on another thread. As a result, the first thread that called the method suspends its work and waits for the second thread to finish execution.

The Thread class has three forms of join() method:

  1. public final void join() throws InterruptedException
  2. public final void join(long millis) throws InterruptedException
  3. public final void join(long millis, int nanos) throws InterruptedException

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

sleep() method in Java blocks a thread for a particular time, which means it pauses the execution of a thread for a specific time. There are two overloaded forms of sleep() method in java.lang.Thread class.

  1. public static void sleep(long millis) throws InterruptedException
  2. public static void sleep(long millis, int nanos) throws InterruptedException

Example Illustrating the Working of sleep() method


public class ThreadsInJava
{
    public static void main(String[] args)
    {
        System.out.println("Before Sleeping");
 
        try
        {
            Thread.sleep(50);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
 
        System.out.println("After Sleeping");
    }
}

Thread.sleep(50) pauses the execution of the current thread for 50 milliseconds.

Output

Before Sleeping
After Sleeping

14. List out the differences between wait() and sleep() method.

wait()sleep()
wait() is a method of Object classsleep() is a method of Thread class
wait() releases lock during synchronizationsleep() method does not release the lock on the object during synchronization
wait() is not a static method.sleep() is a static method
wait() has three overloaded methods:
  • wait()
  • wait(long timeout)
  • wait(long timeout, int nanos)
sleep() has two overloaded methods:
  • sleep(long millis)millis: milliseconds
  • sleep(long millis,int nanos) nanos: Nanoseconds

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. Explain daemon threads.

  • JVM creates daemon threads.
  • They are the low-priority threads that provide the background support and services to the user threads.
  • JVM will not wait for these threads to finish their execution. JVM will exit as soon as all user threads finish their execution.
  • There are two methods for daemon thread available in the Thread class:
    1. public void setDaemon(boolean status) marks the thread as a daemon or a user thread.
    2. public boolean daemon (): It checks whether the thread is a daemon.

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

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 is the default priority of a thread? Can we change it?

The default priority of a thread is the same as that of its parent. Yes, we can change the priority of a thread at any time using the setPriority() method.

Example


public class ThreadPriority 
{
    public static void main(String[] args) 
    {
        Thread t = Thread.currentThread();
         
        System.out.println(t.getPriority());       
         
        t.setPriority(8);
         
        System.out.println(t.getPriority());      
    }
}
    

t.setPriority(8) sets the current thread priority to 8. By default, the priority of the main thread is Thread.NORM_PRIORITY, which is generally 5. This value is printed to the console.

Output

5 
8 

20. Is it possible to make constructors synchronized in Java?

No, the synchronized keyword cannot be used with constructors in Java. The synchronization mechanism in Java is designed to manage access to objects that already exist, ensuring that multiple threads do not interfere with each other when accessing a shared resource.

Java Multithreading Interview Questions for Intermediates

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

Q4. How can I prepare for Java Multithreading interview questions?

 Understand core concepts like thread creation, synchronization, locks, and thread communication. Study the Java Concurrency API, including ExecutorService, Future, CountDownLatch, and Semaphore. 

Q5. Where can I find more resources on Java Multithreading?

You can explore Oracle's official Java documentation, our Java Programming Course, GitHub, etc

Q6. What are the advantages of using multithreading in Java?

  • Improved Performance 
  • Enhanced Responsiveness
  • Simplified Modeling 
  •  Resource Sharing 

Q7. What are common Java Multithreading concepts I should know?

  •  Thread Creation 
  •  Synchronization 
  •  Inter-thread Communication 
  •  Thread Lifecycle 
  •  Concurrency Utilities 
  •  Thread Safety 
  •  Volatile Keyword 
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Project Jul 16 TUE, THU
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Master Class Jul 20 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

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