This tutorial covers important Java multithreading interview questions along with java thread interview questions and java concurrency interview questions.
Table of Contents
1. What is a thread?
A thread is a subprocess that follows a separate execution path. Every thread executes independently even though they share the same process resources. Each thread runs or executes in a different stack frame.
2. What is multithreading in java?
Multithreading is the process of executing one or more threads simultaneously that helps in executing multiple tasks at the same time. Every thread executes independently by sharing the same resources.
3. What are the advantages of multithreading?
- Consumes less memory
- Performance is fast
- More efficient
- Supports multitasking
- Exception in one thread does not affect the other since threads are independent
4. What are the different states in a lifecycle of a thread?
- New
- Runnable
- Running
- Non-Runnable
- Terminated
5. What are the different ways to create a thread?
There are 2 ways to create a thread:
- Extending Thread class
- Implementing Runnable class
6. What is the use of Thread.start() method?
Thread.start() method starts the thread process and used to run the run() method.
7. What are the different constructors of a thread class in Java?
- Thread()
- Thread(String name)
- Thread(Runnable r)
- Thread(Runnable r, String name)
8. Is it possible to start a thread twice?
This is one of the common multithreading java interview questions.
No, we can start a thread twice. When we try to restart the same thread as in the below example, we will get IllegalThreadStateException when it executes the second start() method of the same thread.
public class ThreadDemo extends Thread { public void run() { System.out.println("THread running"); } public static void main(String[] args) { ThreadDemo t = new ThreadDemo(); t.start(); t.start(); } }
Exception in thread "main" THread running java.lang.IllegalThreadStateException at java.base/java.lang.Thread.start(Thread.java:790) at ThreadDemo.main(ThreadDemo.java:11)
9. What are the different methods of a thread that is used for communicating with each other?
- wait() method
- notify() method
- notifyAll() method
10. What is the difference between a user thread and a daemon thread?
User thread | Daemon thread |
---|---|
High priority thread | Low priority thread |
Runs in foreground | Runs in background |
Performs specific complex task | Performs supporting task |
JVM always waits for active user thread to complete before shutdown | JVM does not wait for daemon thread to complete before shutdown |
Created by the Java application for executing some task | Created by the JVM |
It is independent | It depends on the user threads |
11. How to pause the thread execution for a specific time?
We can use the sleep() method to make the thread pause its execution for a specific time. Once it awakes, it changes the state to runnable and executes based on the thread scheduler.
12. What is thread priority?
Every thread has a priority with a value ranging from 1 to 10 where 1 is the lowest and 10 is the highest. The highest priority thread always has the precedence of executing first but also depends on the Thread Scheduler implementation.
13. What is thread scheduler and time slicing?
The thread scheduler is a service that belongs to the operating system that schedules or allocates CPU time for thread execution. Once we create a thread and start it, the thread scheduler decides when to execute the thread based on its implementation.
Time slicing is the process of diving the available CPU time for the runnable threads. This can depend on the thread priority and thread waiting time.
14. What is context switching in multithreading?
Context switching is a process used in multitasking or multithreading where we can store and restore the CPU state of a thread. This helps in continuing the thread execution from the same point where it was paused after a particular time.
15. Why do we call the wait(), notify(), and notifyAll() methods from the synchronized method or block?
All these methods have a dependency on the Object monitor because if a thread is in a wait state, then it leaves the Object monitor and returns until it calls the notify() method. Since all these methods require synchronization with each other, we need to call them only from the synchronized method or block.
16. How to achieve thread-safety in Java?
- Synchronization
- Atomic concurrent class
- Concurrent Lock interface
- volatile keyword
- immutable classes
- Thread-safe classes
17. What is the use of a volatile keyword?
When we declare a variable as volatile, it reads the value of the variable directly from the memory instead of cache.
18. How to create a daemon thread?
We can create a daemon thread using the setDaemon(true) method of the Thread class. We need to use this method before calling the start() method else it will throw IllegalThreadStateException.
19. What is Thread Dump in Java?
A Thread Dump is a group of active threads that are used to analyze bottlenecks and deadlock situations. We can generate thread dump using a profiler, kill-3 command, jstack tool, etc.
20. What is deadlock? How to analyze and avoid a deadlock situation?
A deadlock is a situation in which threads are blocked forever. This occurs when two or more threads access the same resource which depends on each other. In other words, none of the threads get executed wherein one thread waits for the other thread to execute which is already in wait condition.
We can analyze a deadlock situation by looking at the thread dump and searching for threads in the BLOCKED state.
We can avoid deadlock by avoiding the usage of nested locks, waiting infinitely, and locking only what is required.
21. What is the difference between wait() and sleep() methods?
The wait() method is part of the Object class and is used to release the lock whereas the sleep() method is part of the Thread class and does not release any lock.
22. What is the join() method?
The join() method waits for the currently executing task to stop execution until it joins the completed task list. In other words, it waits for the thread to go to the terminated state.
23. What is inter-thread communication?
Inter-thread communication is the process of communication between the synchronized threads and is used to avoid thread polling. This is useful when one thread pauses its execution in the critical state and allows another thread to enter the execution in the same critical state.
24. What are the differences between a process and a thread?
Process | Thread |
---|---|
A process is a program in execution | Thread is a subset of a process |
Processes maintains different address space | Threads maintains same address same |
Context switching is slower | Context switching is faster |
Inter-process communication is slower | Inter-thread communication is faster |
Any change in parent process does not affect the child process | Any change in parent thread will affect the child thread |
25. What is a shutdown hook?
A shutdown hook is a thread that is implicitly called by the JVM to clean up the resources before JVM shutdown either normally or abruptly.
26. When can we interrupt a thread?
We can interrupt a thread when we want the thread to wakeup from the sleep or wait state. We can do this by calling the interrupt() method that throws InterruptedExeception.
27. What is synchronization?
Synchronization is the process of controlling the access of multiple threads to the shared resource. In other words, when one thread uses the shared resource, it locks it so that the other thread cannot use it until it releases the lock. This is very important since it can result in errors if multiple threads try to do the same task at the same time. To avoid this issue, Java introduced the synchronization concept.
We can achieve synchronization in the below 3 ways:
- By synchronization method
- Synchronization block
- static synchronization
28. What is race condition?
A race condition is a serious problem that arises due to improper use of synchronization where multiple threads execute the same task at the same time.
29. What is a thread pool?
A thread pool represents a group of threads that are waiting for a task. The service provider pulls one thread at a time and assigns a task to it. Once it completes, the thread again returns back to the thread pool. Using a thread pool, we can achieve better system stability and better performance.
30. What are the main components of the Concurrency API?
The Concurrency API can be implemented using the various classes and interface of the Concurrency package which are listed below:
- Executor
- ExecutorService
- ScheduledExecutorService
- Future
- TimeUnit
- ThreadFactory
- Locks
- DelayQueue
- BlockingQueue
- Semaphore
- Phaser
- CyclicBarrier
- CountDownLatch
- FarkJoinPool
31. What is the Executor interface in the Concurrency API?
The Executor interface is used to execute a particular task. It belongs to the java.util.concurrent package which contains an execute() method.
32. What is BlockingQueue?
BlockingQueue is the child interface of the Queue interface where it contains methods to wait for available space before inserting a new value and wait for the queue to become non-empty before retrieving a value.
33. What is the difference between Java Callable and Runnable interface?
Both Java Callable and Runnable interfaces are used to execute multiple tasks. Below are the differences:
Callable interface | Runnable interface |
---|---|
Returns a value | Does not return any value |
throws CheckedException | does not throw CheckedException |
Not available prior to Java 5 | Available prior to Java 5 |
34. What is atomic action in Concurrency?
Atomic action is an operation where it performs a single task without any interference of other methods. It is part of the Concurrent package. Once the atomic action starts, we cannot stop or pause it in between. We need to wait for until it completes the full action. All areas and write operations of primitive variables and volatile variables are atomic operations.
35. What is a lock interface in Concurrency?
A lock interface is used to implement synchronization. It is similar to a synchronized block however there are few differences. A lock interface contains the lock() and unlock() method and guarantees the order in which the threads are waiting for execution. Also, it supports timeout operations.
36. What is an ExecutorService interface?
An ExecutorService interface is a subinterface of the Executor interface which has special functions to manage the life cycle.
37. What is the difference between synchronous and asynchronous programming?
In synchronous programming, when a thread starts working on a task, it is available for other tasks only once the assigned task is completed.
In asynchronous programming, multiple threads can perform the same task.
38. What is the difference between the start and run method?
A start method creates a new thread and internally invokes the run method to execute the code for the new thread
The run method executes the code for the existing thread.
39. What is the difference between notify() and notifyAll() method?
The notify() method unblocks a single waiting thread whereas the notifyAll() method unlocks all the waiting threads.
40. Consider there are 3 threads T1, T2, and T3. How can we ensure that T2 is run after T1, and T3 is run after T2?
This is one of the common interview questions on multithreading that is asked. The answer is, we can ensure this by using the join() method.
Conclusion
In this tutorial, we have covered the top java multithreading questions, interview questions on multithreading, java thread interview question, multithreading java interview questions, java multithreading questions, java concurrency interview questions.