Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
This article lists some of the most common Java multithreading interview questions. These questions can be a way to revise for experienced programmers or a primer for novice programmers to get a handle on Java multithreading interview questions.
Let's begin our journey through the most commonly asked Java multithreading interview questions!
What is Multithreading in Java? Why is it important?
Multithreading in Java is a programming concept that refers to small tasks running simultaneously. Let's take an example of multithreading as our computer or mobile phones, which allows us to run various tasks at once. Its main purpose is to enable multiple threads to run simultaneously, maximizing CPU usage and improving program execution speed. This Java feature allows a program to be divided into multiple threads for faster and easier execution.
Multithreading Interview Questions in Java for Freshers
1.What is a thread in Java?
Threads are referred to as the smallest parts of a process that simply let a program execute efficiently with other parts or threads of the process at the same time. They share a common address space and are independent of each other. In Java, there are two ways of creating threads:
Via Thread class
Via Runnable interface
2. What are the two ways of implementing threads in Java?
The two ways of implementing threads in Java are as follows:
Via Thread class
Java
Java
class SampleMultithreading extends Thread { public void run() { System.out.println("My thread is currently running."); }
public static void main(String args[]) { SampleMultithreading obj = new SampleMultithreading(); obj.start(); } }
You can also try this code with Online Java Compiler
Multitasking is a feature in an operating system that divides system resources among tasks/processes and switches between the tasks/processes while they are executing over and over again. This gives the perception of 2 or more tasks running concurrently. Multitasking is of two types:
Process-based multitasking
Thread-based multitasking
4. What are the benefits of using Multithreading?
Multithreading possesses various benefits described below:
It increases the use of CPU resources.
Does not get blocked easily if some parts of it are blocked
It allows the programs to utilize maximum CPU time
Improves the responsiveness of the program.
It allows parallelism.
5. What is a thread lifecycle?
A thread at any instant of time can be found in any one of the following states:
New
Runnable
Blocked
Waiting
Timed waiting
Terminated
6. What is the difference between a thread and a process?
A program in execution is called a process, while the smallest independent units in a process are called a thread.
Parameter
Thread
Thread
Definition
Smallest unit of a process.
A program in execution.
Creation Time
Requires less time for creation.
Requires more time for creation.
Termination Time
Requires less time for termination.
Requires more time for termination.
Switching Time
Faster switching between threads.
Slower switching between processes.
Communication Speed
Inter-thread communication is faster.
Inter-process communication is slower and more expensive.
Dependency
Threads are dependent on the parent process.
Processes are independent of each other.
7. What is the task of the main thread?
The main Thread is a thread contained in every program created by the JVM at the start of the program when the main() function is invoked with the main Thread as depicted from the output perceived from pseudo-code illustration.
System.out.println(Thread.getname().currentthread());
Output: main
8. What are the different types of threads in Java?
There are two types of threads in Java as follows:
User Thread(Non-daemon thread)
Daemon Thread
Parameter
User Thread
Daemon Thread
Definition
Threads created by the user for executing tasks concurrently.
Threads created by the JVM for supporting tasks.
Creation
Explicitly created by the user.
Automatically created by the JVM.
JVM Behavior
JVM waits for user threads to finish before termination.
JVM does not wait for daemon threads to finish before termination.
Priority
High priority threads.
Low priority threads.
Purpose
Used for critical tasks.
Used for supporting tasks.
9. What is the start() and run() method of Thread class?
Start(): The start() method is used to start or begin the execution of a newly created thread. When the start() method is called, a new thread is created, and this newly created Thread executes the task that is kept in the run() method. One can call the start() method only once.
run(): The run() method is used to start or begin the execution of the same Thread. When the run() method is called, no new thread is created, as in the case of the start() method. This method is executed by the current Thread. One can call the run() method multiple times.
10. How to set the name of the thread?
A method named as setName() is there which is used to change or set the names of the threads.
thread_class_object.setName("Name_thread_here");
You can also try this code with Online Java Compiler
Garbage collection is a process of managing memory automatically. A garbage collector finds objects that are no longer required by the program and then deletes or removes these unused objects to free up memory space. It uses several GC algorithms. One popular name of the algorithm is Mark and Sweep.
12. What is thread Starvation?
When low-priority threads do not get CPU for their execution because high-priority threads occupy the CPU for long periods of time, this phenomenon is called thread starvation. This makes the Thread unable to progress.
13. What is thread priority?
In Java, every Thread has a priority which is represented by the numbers from 1 to 10. The default priority is set to 5, the minimum priority is set to one, and the maximum priority is set to 10. Here, three constants are defined as NORM_PRIORITY, MIN_PRIORITY, and MAX_PRIORITY.
14. What is context switching
Context Switching is referred to as switching the CPU from one Thread or process to another one. In context switching, the state of the Thread is stored so that the next time the execution of the Thread is required, it can be resumed from the same point.
15. What do you mean by inter-thread communication?
It is a 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.
16. What do you mean by finalize() method?
The finalize() method in Java was defined in the Object class before Java version 9. It was supposed to be used for performing cleanup operations on an object before it was garbage collected. After the release of Java 9, this method has been deprecated and it is no longer recommended for managing memory.
Multithreading Interview Questions in Java for Experienced
17. What is the purpose of the finalize() method?
The finalize method in Java is used for performing cleanup operations on objects about to be garbage collected by the JVM. When an object becomes eligible for garbage collection, the JVM checks for a finalize() method and calls it before cleaning the memory. This method can be overridden to define custom cleanup logic. Let's look at the basic syntax of this overriding this method.
class MyClass {
// Constructor and other methods
// Custom finalize() method for cleanup
protected void finalize() {
// Perform resource cleanup here
}
}
18. What is a semaphore?
Semaphore is regarded as a thread synchronization system that is usually required to control and manage the access to the shared resource using counters. 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.
19. How to make a user thread to daemon thread?
There are two methods in the thread class that is used to make a user thread into a daemon thread.First, the setDaemon() method converts the user thread to the daemon thread and vice-versa. After this, the isDaemon() method is used, which returns a boolean true if the Thread is daemon. Else returns false if it is a non-daemon thread.
20. 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.
21. What are the tasks of the start() method?
The main task of the start() method is to register the Thread with the thread scheduler, so one can tell what child thread should perform, when, and how it will be scheduled that is handled by the thread scheduler. The second task is to call the corresponding run() method.
22. Explain the difference between class lock and object lock?
A class lock is present within the class and prevents simultaneous access to a concurrent static method or block. While object lock is related to the instance of a class that allows simultaneous access to concurrent methods or blocks in different objects.
23. Explain the difference between User thread and Daemon thread?
A user thread is also known as high priority thread. The Java virtual machine completes all the user threads before terminating. While the daemon thread is also known as low priority thread, and they are mainly used as background tasks and provide services to the user thread.
24. What are the wait() and sleep() methods?
The wait() and sleep() methods are used to stop any running thread and convert them into a non-runnable state. The wait method is mostly used for thread sync, and the sleep() method is used to pause the running threads.
25. Explain the difference between notify() and notifyAll()?
The notify() method is used to alert only one waiting thread among many waiting threads, while the notifyAll() method is used to send notifications to all the waiting threads. notify() method uses less memory and CPU in comparison to the notifyAll() method.
26. What do you mean by thread pool?
A thread pool can be considered a collection of all the threads that are ready to perform the tasks. It also increases the reusability of the threads as it does not create and destroy the threads each time.
27. Can two threads execute two methods (static and non-static concurrently)?
Yes, two threads can run two different methods (one static and one non-static) of the same class. However, it is important to note that unexpected behavior can occur because the locking mechanism will lock two different things: the object and the class itself, which means both methods will execute simultaneously, and a shared state can be mutated.
28. What is meant by volatile variables in Java?
In Java, the volatile keyword is used to declare a variable as volatile, which means changes made to it by one thread will be immediately visible to other threads. You can use this keyword to define simple flags or status indicators frequently checked by many threads.
29. What’s the purpose of the join() method?
The join() method in Java is provided by the Thread class and used for thread synchronization and coordination. This method allows you to make a thread wait for the completion of another thread.
For example, there are two threads, A and B. If thread A calls the join() method on thread B, thread A will pause its execution and wait for thread B to complete.
30. How do synchronized methods and synchronized blocks differ, and which one is the preferred choice?
Synchronized methods and blocks in Java are used to achieve thread synchronization and prevent multiple threads from concurrently accessing critical code sections. The choice between synchronized methods and synchronized blocks depends on your specific requirements:
Synchronized Methods: Use synchronized methods when you want to synchronize the entire method and there's no need to synchronize different parts of the method separately.
Synchronized Blocks: Use synchronized blocks when you need more control over synchronization, and you want to synchronize specific sections of code. Synchronized blocks are more flexible and allow for finer-grained synchronization.
31. What is meant by deadlock and how it can occur?
A deadlock is a situation in which two or more threads are blocked for an infinite time, and they all wait for each other to release their resources. Deadlock can occur due to mutual exclusion, holding and waiting of threads or when a circular chain of two or more threads exists.
Frequently Asked Questions
Is it possible to call the run() method directly to start a new thread?
No, it's not possible at all. You need to call the start method to create a new thread otherwise it will execute in the current thread.
Can we Overload run() method?
Yes, it is possible to overload run() by passing parameters to it and also keeping a check over to comment down @override from the run() method.
Why is multithreading required?
Multithreading is required in order to enhance the performance and to improve the responsiveness of the process.
Conclusion
In conclusion, multithreading is a crucial aspect of Java and modern software development, enhancing program efficiency and reducing resource usage. This article covered key multithreading interview questions and answers to help you succeed in your interviews.