Introduction to Multithreading Interview Questions and Answers in Java
In Java, Multithreading involves executing two or more threads simultaneously, enhancing process speed based on system capacity. Multithreading processes the smallest units concurrently, facilitating faster execution. Developers use it for tasks like animation, gaming, and managing large applications, contributing to memory space and time efficiency.
Now, if you are looking for a job related to Multithreading in Java, you need to prepare for the Multithreading Interview Questions in Java. Every interview is indeed different based on the job profiles. Here, we have prepared the important Multithreading Interview Questions in Java with their Answers, which will help you succeed in your interview.
This article will present the 40 most important and frequently asked questions about multithreading interview questions in Java.
Q1. Explain the different states of Thread.
Answer:
The states of the thread are also referred to as the Lifecycle of a Thread. Below are the different states of Thread:
-
- New: It means the thread is in a new state and needs to create the instance of the thread class before the invocation of the start method.
- Runnable: After invoking the start method, the thread is in a runnable state, and the scheduler has not selected it to be a running thread.
- Running: When the thread scheduler is selected, it is in a running state.
- Blocked: It is also known as Non-Runnable. When the thread is not eligible to run, it is still alive.
- Terminated: This is the state when it exits the run method or is in the dead state.
Q2. What is the thread in Java?
Answer: The thread refers to a small unit that takes less time to get executed. It is mainly independent of the path of execution. It is one of the ways to take advantage of multiple CPUs available in the machine. With the help of multiple threads, the process of the CPU task becomes faster. Java is majorly used for providing support to multithreading. Java supports multithreading to take advantage of multiple processors and improve program performance. Extending the Thread class or implementing the Runnable interface are two ways to create threads.
Q3. Explain the difference between thread and process in JAVA.
Answer: The thread is the smallest task of execution within the process. The process is a self-contained execution environment having more than one thread or multiple threads. Threads are the subdivision of the process. The thread has direct access to the process’s data segment, whereas the process has its own copy of the data segment. Thread mainly shares the address created by the process, and the process has its own address.
The thread can be easily created, and process creation needs a lot of things to do. The thread can easily communicate with other threads, whereas the process can easily communicate with the child process, but interprocess communication is difficult. The thread has its own stack, whereas the process shares the memory resources like heap memory, etc. If any change has been done in the thread, it will affect all the threads, but in the process, it does not affect other processes.
Q4. Explain about Java Memory Model.
Answer: These are the common multithreading Interview Questions in Java asked in an interview. Several responsibilities normally need to be followed by a multithreading tester in the current IT industry.
The Java Memory Model establishes a specific set of rules that Java programs must adhere to in order to exhibit consistent behavior across various memory architectures, CPUs, and operating systems. These rules play a crucial role in multithreading.. The Java memory model helps to distinguish the changes done in one of the threads, and that change should also be visible to other threads. This mod is a program order that says that each thread’s action happens before every thread comes later in the program order.
Q5. Explain the use of Volatile variables in Java Multithreading.
Answer: The volatile keyword or variable ensures that shared or instance variables receive constant updates whenever multiple threads make changes. It is a special modifier applicable only to instance variables, not methods. Declaring a field as volatile in Java ensures the Java memory model guarantees consistent values for that variable across all threads. The program always reads the value of the volatile variable from the main memory, thereby reducing the likelihood of memory consistency errors. Moreover, a Java volatile variable representing an object reference can be null. Applying the volatile keyword is necessary when a variable is used across multiple threads.
Q6. Explain the race condition in threads.
Answer: The race condition occurs when there is a race between multiple threads. This race condition is mainly caused due to some programming bugs or errors. The thread that needs to be executed initially lost the race and then executed the second and some change in the behavior of code that is referred to as non-deterministic bugs. It becomes one of the difficult bugs to find out and reproduce because of the random nature of threads.
Q7. Explain the fork-join framework in Java.
Answer: The fork-join framework is introduced in JDK7. It is a powerful tool for Java developers to take advantage of multiple processors of today’s world servers. It is mainly designed for work that can be divided into smaller pieces. The main goal is to use the available processing power to raise application performance. It mainly used the work-stealing algorithm.
Q8. Explain the thread pool and its use in Java.
Answer: The pool of thread is known as a thread pool. The thread is generally called as a worker thread. The creation of a thread is costly in many terms, as time and resources. When you create the thread at the time of requesting the process, generally, it slows down the processor response time, and only some limit in the number of threads can be created. So, because of these two major issues, the thread pool has been created. In Java, Java API allows us to create different types of thread pools, like a single thread pool, which takes only one process at a time. The other is a fixed thread pool that takes a fixed number of threads. Then there is a cached thread pool, an expandable thread pool and mainly suitable for many tasks.
Q9. How can the data be shared between the threads?
Answer: These are the most popular multithreading Interview Questions in Java asked in an interview. Some popular test cases in the current IT industry.
The data can be shared between threads with the help of using the shared object or concurrent data structure like a Blocking queue. It mainly follows the producer-consumer pattern using wait and notifies methods that involve sharing an object between the two threads.
Q10. How are threads distributed in stack and heap memory?
Answer: In Java, each thread has its own stack, which is used to store local variables, method parameters, and call stack. Heap memory is a common memory that is being shared by all the threads.
Q11. Distinguish between a thread and a process.
Answer:
Feature | Process | Thread |
Definition | An autonomous program running. | A process’s lightweight unit. |
Execution | Operates on its own. | Operates within a process’s framework. |
Communication | Requires communication between processes. | Communication made easier and data space shared. |
Synchronization | More remote and possibly requiring more overhead. | Requires shared data synchronization mechanisms. |
Resource Overhead | Greater (differing memory spaces). | Lower (shares the process’s resources). |
Creation Time | Slower and requiring more resources. | Quicker and with less overhead needed. |
Fault Tolerance | More resilient. | Failure could impact the entire process if it is not as strong. |
Q12. What is the Java wait() method used for?
Answer: Java uses the notify() and notifyAll() methods in conjunction with the wait() method to implement synchronization and inter-thread communication. The Object class, which is the foundational class for all Java classes, contains these methods. Syntax given below :
public final void wait() throws InterruptedException
This means that if you use wait(), you should either declare that the method that calls wait() throws this exception or catch the InterruptedException.
Q13. Differentiate between the user Thread and the daemon Thread?
Answer: A thread created in Java is termed a User Thread. A Daemon Thread always runs in the background, and its complete life cycle depends on the main thread. A daemon thread running in the background will not prevent JVM from terminating it. Child thread created from a daemon thread will also be a daemon thread.
Q14. What are the different ways of creating a Thread in Java?
Answer:
Threads in Java can be created in two ways:
- By extending Thread class.
class MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
}
}
// Creating and starting the thread
MyThread myThread = new MyThread();
myThread.start();
- By implementing Runnable Interface.
class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
}
}
// Creating a thread using the Runnable interface
Thread myThread = new Thread(new MyRunnable());
myThread.start();
Q15. What is the lifecycle of Thread in JAVA?
Answer: There are common Java interview questions on multithreading asked in an interview. Following is the life cycle of a Thread:
- New
- Runnable.
- Running.
- Blocked.
- Terminated.
Q16. What happens if we call the run () method of a Thread class?
Answer: Calling the run () method directly will compile and execute the program successfully, but the same program will not be treated as Thread because no new call stack will be created, and the program starts its execution in the same call stack where the main is running.
To create a Thread that should run with a new call stack, one has to use the start () method of the Thread class.
Q17. Can we pause the execution of a Thread at a specific time?
Answer: Yes, this can be achieved in Java by calling the sleep () of the Thread class. The sleep () method also takes an argument that indicates the time in milliseconds.
Q18. How can we achieve the scheduling of threads in Java?
Answer: Yes, thread scheduling in Java is possible. Threads in Java can be scheduled in two ways, i.e., Time Slicing and Pre-emptive Scheduling.
Let us move to the next Java Interview Questions on Multithreading.
Q19. Can a Thread be started twice?
Answer: No, a thread cannot be started twice. If we try to start a thread twice, it will throw “java.lang.IllegalThreadStateException”.
Q20. What is a shutdown hook in Java?
Answer: These are the most popular Java Interview Questions on Multithreading asked in an interview. A shutdown hook is a mechanism that is used to clean up resources when the JVM shuts down normally or abruptly.
Q21. What is volatile?
Answer: Volatile is a keyword in java, and it can be used with variables. If a variable is declared as volatile, all the threads will read the value of the same variable from the main memory rather than from the cache; thus, it prevents error reading when multiple threads use the same variable in their operations.
Q22. How do you implement a thread in JAVA?
Answer: Java provides two ways to implement threads in a program. Interface java.Lang.Runnable has an instance of Java.lang.A line that requires a task to execute through an instance. The Thread class already implements Runnable, so a user can directly override the run() method by extending the Thread class or implementing the Runnable interface.
Q23. When to use Runnable and when to use Thread in Java?
Answer: Java provides better to implement the Runnable interface rather than extending the Thread class because Java only allows for single inheritance. Because a class can implement multiple interfaces but only extend one class, this provides greater flexibility when it comes to sharing code between classes.
Q24. Why is it said that Thread’s behavior is unpredictable?
Answer: The reason for this is the thread scheduler which handles the execution of threads. The scheduler may perform different performances on Windows, UNIX, and LINUX platforms. While executing, the same thread may give different outputs on various platforms, sometimes even on the same platform. To solve this, a user can create the same Runnable object, create run() loops in both threads and start both lines together.
Q25. What is a volatile variable in Java, and what is its significance?
Answer: Java facilitates users to share variables present in different threads. A volatile variable acts as a unique modifier that can be used only for instance variables. It provides that a write will happen before any consequent read. The Java memory model ensures the consistency of this variable.
Q26. What is the use of the synchronized keyword? What is the difference between synchronized and volatile keywords?
Answer: The synchronized keyword is used when the goal is to allow only one thread to run at a time in a specific section of code. It can be applied to define four different types of blocks, as shown below:
- Instance methods
- Static methods
- Code blocks inside instance methods
- Code blocks inside static methods
It can be declared as follows:
Public synchronized void example () {}
A volatile variable will never land up in a deadlock as it does not require obtaining any lock. While in synchronized variables, it may end up in a draw if they are not done correctly.
Q27. Why methods like wait(), notify(), and notify all() are present in the object class and not in the Thread class?
Answer: Object class has monitors that allow the Thread to lock an object, while Thread does not have any monitors. The object class’s monitor checks for the thing to see if it is available. Thread class having these methods would not help as multiple threads exist on an object, not vice versa.
Q28. Explain the difference between sleep() and wait() methods.
Answer:
- When the wait() method is called, the monitor moves the Thread from running to waiting for the state. Once a thread is in wait(), then it can move to runnable only when it has notified () or told all () for that object. The scheduler changes the state after this. While in the sleep() method, the state is changed to wait and will return to runnable only after sleep time.
- The wait () method is a part of Java.lang.Object class, while sleep() is a part of Java.lang.Thread class.
Q29. How to force start a thread in Java?
Answer: In Java, multithreading, one cannot force start a thread. Only thread schedulers can control lines and are not exposed to any API for control.
Q30. Does Thread leave object lock when wait() and sleep() methods are called?
Answer: A thread in the sleep() method does not leave the lock and moves to the waiting state. The Thread waits for sleep time to get over.
Q31. Explain the advantages of Multithreading.
Answer :
When it comes to software development, multithreading has several benefits:
- Enhanced Performance: By utilizing multiple processor cores to execute tasks in parallel, multithreading improves the overall performance of applications.
- Responsiveness: Multithreading helps applications with graphical user interfaces stay responsive by running background tasks simultaneously.
- Resource Utilization: By allowing some threads to continue processing while others wait for I/O operations, efficient use of the system’s resources is achieved, maximizing the use of CPU and I/O devices.
- Maintainability and modularity: Multithreading encourages modular design by assigning distinct threads to handle different functions, which results in code that is easier to read and maintain.
- Asynchronous Programming: Multithreading makes it possible for tasks to run independently of the main program flow, which is essential for managing events or asynchronous input/output tasks.
Q32. How does time slicing differ from preemptive scheduling?
Answer:
1. Preemptive Scheduling: It is a scheduling technique used by operating systems that allows the system to start or stop a task that is presently underway in order to focus on a higher priority task.
Example: In a preemptive scheduling system, even if a lower-priority task is presently running, it may be preempted from execution if a higher-priority task becomes ready to run.
2. Round Robin Scheduling (Time Slicing): It is a scheduling technique where each process or thread is assigned a fixed time slot or quantum during which it can execute. Once the time slice expires, the next task in the queue is given CPU time.
For instance, if the time slice is set to 10 milliseconds and there are three tasks (A, B, and C), each task receives 10 milliseconds of CPU time in a cyclic fashion (A for 10 ms, then B for 10 ms, and so on).
Q33. What is deadlock?
Answer: Every thread in a system that is waiting for a resource that another waiting thread is holding causes a deadlock. In this case, all of the threads are in a universal waiting state because none of them can continue executing. A deadlock occurs when there is no opportunity for any thread to execute, leading to a halt. Complex circumstances known as deadlocks can impair a program’s regular runtime and possibly lead to coding problems. Maintaining the system’s performance and stability requires controlling and avoiding deadlocks.
Q34. How can a deadlock situation be identified? How is it easily avoidable?
Answer: Tools that display blocked threads, such as thread dumps, can be used to identify deadlocks. TryLock with timeouts, acquiring locks in a consistent order, and reducing lock contention are ways to prevent deadlocks. To lower the chance of deadlocks, properly design multithreaded programs and make use of higher-level concurrency tools.
Q35. Is there a stack for every thread in multithreaded programming?
Answer: Yes, every thread in multithreaded programming has a separate stack. Local variables and details about each thread’s function calls are kept on the stack. Each thread will function independently and have a dedicated area to manage its execution context because of this division.
Q36. How is a thread’s safety achieved?
Answer: A class is considered thread-safe when multiple threads can use its methods or objects concurrently without experiencing conflicts. In multithreaded programming, achieving thread safety is essential to avoiding race situations. This can be done in a few different ways:
- Synchronization: Limiting access to shared resources by employing locks and other mechanisms to make sure that only one thread at a time can access crucial areas.
- Volatile Keyword: Designating variables as volatile ensures consistency by making changes made to the variable by one thread visible to other threads.
- Lock-Based Mechanism: This technique uses explicit locks, like ReentrantLock, to control access to important code segments and stop thread interference.
- Atomic wrapper classes: (such as AtomicInteger and AtomicBoolean) for operations that must be carried out atomically without the need for explicit.
Q37. Tell me the difference between User thread and Daemon thread?
Answer:
Characteristic | User Threads |
Daemon Threads |
Creation and Control | created and managed by the user or the application. | The application or user creates and controls these threads, but they can be explicitly set as daemon threads using the setDaemon(true) method. |
JVM Termination Impact | JVM will wait for user threads to complete before exiting. | JVM can exit even if daemon threads are still running. Daemon threads are abruptly stopped if all user threads have finished their execution. |
Example (Java) |
|
|
Q38. How are daemon threads made?
Answer: The Thread class in Java provides the setDaemon(boolean on) method, which can be used to create daemon threads. When all non-daemon threads have finished running, a daemon thread operates in the background and does not stop the Java Virtual Machine (JVM) from shutting down.
Here’s an easy illustration:
public class DaemonThreadExample {
public static void main(String[] args) {
Thread daemonThread = new Thread(() -> {
while (true) {
// Do some background tasks
System.out.println("Daemon Thread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Setting the thread as daemon
daemonThread.setDaemon(true);
// Starting the daemon thread
daemonThread.start();
// Main thread
System.out.println("Main thread is finished");
}
}
Output:
Explanation:
The daemonThread.setDaemon(true) line in this example designates the thread as a daemon thread. Regardless of its state, the daemon thread will end when the main thread completes its execution and the JVM terminates.
It is crucial to remember that a thread will throw an IllegalThreadStateException if it is not started as a daemon. You are unable to alter a thread’s daemon status once it has begun.
Q39. How do notify() and notifyAll() differ from one another?
Answer:
1. notify():
- Wakes up one of the threads that are currently waiting on the object.
- The scheduling policy of the JVM determines which thread will be notified, and this decision is not guaranteed.
2. notifyAll():
- Wakes up all the threads that are currently waiting on the object.
- Usually makes sure that every thread in line has an opportunity to obtain the lock and verify the altered state.
Q40. What does it mean to be in a deadlock and when can it happen?
Answer: Multiple processes create a deadlock in computing when they become stuck holding resources, waiting for another process to acquire that resource. This situation prevents any progress and results in mutual blocking between the processes.
When the following four requirements referred to as the Coffman conditions—are satisfied, a deadlock usually results:
- Mutual Exclusion: One or more resources must be kept in a non-sharable mode, which limits the resource’s use to a single process at a time.
- Hold and Wait: A process needs to be holding one resource at a time while it waits to obtain more resources that other processes are holding.
- No Preemption: Resources must be released willingly from a process; they cannot be taken away by force.
- Circular Wait: When two or more processes are in a circular chain, each process is waiting for a resource that the subsequent process in the chain is holding.
Recommended Articles
This has been a guide to the list of Multithreading Interview Questions and Answers in Java so that the candidate can crackdown these Interview Questions in Java easily. In this post, we have studied the top multithreading interview questions in Java, which are often asked in interviews. You may also look at the following articles to learn more –