Skip to main content

Multi-threading Interview Questions in Java


Multi-threading




1. What is a Thread in Java?

A thread in Java is a lightweight process that runs within another process or thread. It is an independent path of execution in an application. JVM gives each thread its own method-call stack. When we start JVM, Java starts one thread. This thread calls the main method of the class passed in argument to java call.

2. What is the priority of a Thread and how it is used in scheduling?

In Java, every Thread has a priority. This priority is specified as a number between 1 to 10. Scheduler in Java schedules different threads based on the priority of a thread. It is also known as pre-emptive scheduling. The thread with higher priority gets preference in execution over a thread with lower priority.

3. What is the default priority of a thread in Java?

In Java, a new thread gets the same priority as the priority of the parent thread that creates it. Default priority of a thread is 5 (NORM_PRIORITY).

4. What are the three different priorities that can be set on a Thread in Java?

We can set following three priorities on a Thread object in Java:
1.     MIN_PRIORITY: This is the minimum priority that a thread can have.
2.     NORM_PRIORITY: This is the default priority that is assigned to a thread.
3.     MAX_PRIORITY: This is the maximum priority that a thread can have.
Default priority of a thread is 5 NORM_PRIORITY. The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

5. What is the purpose of join() method in Thread class?

In Java, Thread Scheduler controls thread scheduling. But we can use join() method on a thread to make current thread to wait for another thread to finish. When we use join(), the current thread stops executing. It wait for the thread on which join() is called to finish. This makes sure that current thread will continue only after the thread it joined finished running. Consider following example:
Public class ThreadJoin {
Thread importantThread = new Thread(new Runnable()
{
public void run () {//do something}
});
Thread currentThread = new Thread(new Runnable()
{
public void run () {//do something}
});
importantThread.start(); // Line 1
importantThread.join(); // Line 2
currentThread.start(); // Line 3
}
In the above example, main thread is executing. On Line 1, a new thread called importantThread is ready to run. But at Line 2, main thread joins the importantThread. Now it lets importantTread to finish and then it moves to Line 3. So currentThread at Line 3 will not start till the importantThread has finished.

6. What is the fundamental difference between wait() and sleep() methods?

The main difference between wait() and sleep() is that wait is an Object level method, whereas sleep() is a static method in Thread class. A waiting thread can be woken up by another thread by calling notify() on the monitor which is being waited on. But a sleeping thread cannot be woken up. A wait() and notify() has to happen within the same block that is synchronized on the monitor object. When we call wait() the current thread releases the monitor and goes to waiting state. Then another thread calls notify() to wake it up. In case of sleep() current thread does not release the monitor or locks. It just sleeps for some pre-defined time period.

7.Is it possible to call run() method instead of start() on a thread in Java?

Yes. We can call run() method of a thread. But it does not work as a separate thread. It will just work as a normal object in main thread and there will not be context switching between the threads.

8. How Multi-threading works in Java?

Java provides support for Multithreading. In a Multithreading environment, one process can execute multiple threads in parallel at the same time. In Java, you can create process and then create multiple threads from that process. Each process can execute in parallel to perform independent tasks. Java provides methods like- start(), notify(), wait(), sleep() etc. to maintain a multi-threading environment.

9. What are the advantages of Multithreading?

Main advantages of Multithreading are:
1.     Improved performance: We can improve performance of a job by Multi-threading.
2.     Simultaneous access to Multiple Applications: We can access multiple applications from a process by doing multithreading
3.     Reduced number of Servers required: With Multithreading we need lesser number of servers, since one process can spawn multiple threads.
4.     Simplified Coding: In certain scenarios, it is easier to code multiple threads than managing it from same thread.

10. What are the disadvantages of Multithreading?

There are certain downsides to Multithreading. These are:
1.     Difficult to Debug: Multithreading code is difficult to debug in case of an issue.
2.     Difficult to manage concurrency: Due to multiple threads, we may experience different kinds of issues.
3.     Difficulty of porting code: It is difficult to convert existing single threaded code into multi-threading code.
4.     Deadlocks: In case of multi-threading we can experience deadlocks in threads that are waiting for same resource.

11. What is a Thread in Java?

In Java, a thread is a lightweight process that runs within another process or thread. It is an independent path of execution in an application. Each thread runs in a separate stack frame. By default Java starts one thread when the main method of a class is called.

12. What is a Thread’s priority and how it is used in scheduling?

In Java, every Thread has a priority. This priority is specified as an integer value. The priority value is used in scheduling to pick up the thread with higher priority for execution. The threads with higher priority get more preference in execution than the threads with lower priority. The task scheduler schedules the higher priority threads first, followed by the lower priority threads.

13. What are the differences between Pre-emptive Scheduling Scheduler and Time Slicing  Scheduler?
In Pre-emptive scheduling, the highest priority task will keep getting time to execute until it goes to waiting state or dead state or a task with higher priority comes into queue for scheduling. In Time slicing scheduling, every task gets a predefined slice of time for execution, and then it goes to the pool of tasks ready for execution. The scheduler picks up the next task for execution, based on priority and various other factors.

14. Is it possible to call run() method instead of start() on a thread in Java?
Yes. We can call run() method of a thread. But it does not work as a separate thread. It will just work as a normal object in main thread and there will not be context-switching between the threads.

15. How will you make a user thread into daemon thread if it has already started?
No. We cannot make a user thread to daemon thread once it has already started. If we do it by calling setDaemon(), it will throw IllegalThreadStateException

16. Can we start a thread two times in Java?
No. We can call start() method only once on a thread in Java. If we call it twice, it will give us exception.

17.In what scenarios can we interrupt a thread?
We can interrupt a thread if we want to wake it up from the sleep or wait state.

18. In Java, is it possible to lock an object for exclusive use by a thread?
Yes. We can use synchronized block to lock an object. The locked object is inaccessible to any other thread. Only the thread that has locked it can access it.

19. How notify() method is different from notifyAll() method?
In Java, notify() method is used to unblock a specific thread that is in waiting stated. Whereas, notifyAll() method is used to unblock all the threads that are in waiting state.

20. What is a daemon thread in Java?
A daemon thread in Java is a low priority thread that does not prevent the JVM from exiting when the program finishes. The thread keeps running. Garbage Collection is an example of daemon thread.

21. How can we make a regular thread Daemon thread in Java?
We can call setDaemon(boolean) method to change a thread to daemon thread before the thread starts.

22. How will you make a user thread into daemon thread if it has already started?
No. We cannot make a user thread to daemon thread once it has already started. If we do it by calling setDaemon(), it will throw IllegalThreadStateException.

23. Can we start a thread two times in Java?
No. We can call start() method only once on a thread in Java. If we call it twice, it will give us exception.

24. What is a Shutdown hook in Java?
The shutdown hook is a thread that is invoked implicitly by JVM just before the shut down. It can be used to clean up unused resources etc. We can use java.lang.Runtime.addShutdownHook (Thread hook) method to register a new virtual-machine shutdown hook.

25. What is synchronization in Java?
The concept of Synchronization in Java is used in Multi-threading programming. It is a feature in Java that helps in controlling the access of multiple threads to a shared resource. It is used to prevent Deadlock between multiple threads.

26. What is the purpose of Synchronized block in Java?
Synchronized block has many uses in Java multi-threading environment. Some of the uses are:
It can prevent thread interference It is also used to avoid memory inconsistency issues In general, scope of synchronized block is smaller than the scope of a method.

27.What is static synchronization?
We can make a static method as synchronized in Java. Adding synchronized keyword to a static method can do this. In static synchronization, the lock is on class not on object.

28. What is a Deadlock situation?
A Deadlock is a situation in which two or more threads are waiting on each other to release a resource. Each thread is waiting for a resource that is held by the other waiting thread. At times there is a circular wait when more than two threads are waiting on each other’s resources.

29. What is the meaning of concurrency?
Concurrency is the ability of a program to execute several programs simultaneously. This is achieved by distributing computations over multiple CPU cores of a machine or even over different machines within the same network. It can increase the speed of execution of the overall program in multi-processor or multi-core system.

30. What is the main difference between process and thread?
As such both process and thread are independent sequences of execution. The main difference is that a thread runs in a shared memory space, where as a process runs in its own memory space. A process runs the execution in an environment provided by the operating system. A process has its own set of private resources (e.g. memory, open files, etc.). A thread lives within a process and shares the resources likememory, open files etc. with the other threads of the same process. This ability to share resources between different threads makes thread more suitable for tasks where performance is a significant factor.

31. What is a process and thread in the context of Java?
In Java, a process refers to the running of Java Virtual Machine (JVM). But a thread lives within a JVM and it can be created or stopped by the Java application at runtime.

32. What is a Scheduler?
A scheduler is a program that is the implementation of a scheduling algorithm to manage access of processes and threads to limited resource like CPU or an I/O channel. The goal of most scheduling algorithms is to provide load balancing for the available processes/threads and to guarantee that each process/thread will get a reasonable time frame to access the requested resource exclusively.

33. What is the minimum number of Threads in a Java program?
In a JVM, each Java program is executed within the main process that starts with java.exe. Therefore each Java application has at least one thread.

34. What are the properties of a Java thread?
Each Java thread has following properties:
Identifier: An identifier of type long that is unique within the JVM
Name: A name of type String
Priority: Priority of type int
State: A state of type java.lang.Thread.State
Group: A thread group the thread belongs to


35. What are the different states of a Thread in Java?
Following are the different states of a Thread in Java:
New: In the New state the thread has not yet.
Runnable: A thread executing in the JVM is in Runnable state.
Blocked: A thread waiting for a monitor lock is in Blocked state.
Waiting: A thread waiting indefinitely for another thread to perform a particular action is in Waiting state.
Timed_waiting: A thread waiting for another thread to perform an action for up to a specified waiting time is in Timed_waiting state.
Terminated: A thread that has exited is in Terminated state.

36. How will you set the priority of a thread in Java?
The priority of a thread in Java can be set by using setPriority(int priority) method. We can use constant Thread.MAX_PRIORITY to set the maximum priority of a thread. We can use constant Thread.MIN_PRIORITY to set the minimum priority of a thread. Or we can use constant Thread.NORM_PRIORITY to set the default priority of a thread.

37. What is the purpose of Thread Groups in Java?
In Java, every thread belongs to a group of threads. The JDK class java.lang.ThreadGroup provides methods to handle a whole group of Threads. With the help of these methods we can interrupt all threads of a group or set the maximum priority of all threads of a group. So a thread group is used for taking collective actions on a group of threads.

38. Why we should not stop a thread by calling its stop() method?
The stop() method in Thread class is a deprecated method. Its use is not recommended. When we call stop() method, the thread unlocks all monitors that it has acquired. If any locked object was in an inconsistent state, this state gets visible to all other threads. It can cause unexpected behavior when other threads work on this inconsistent object. So calling stop() method to stop a thread is not advisable.

39. How will you create a Thread in Java?
There are two main ways to create a thread in Java.
Extend Thread class: We can extend java.lang.Thread class and implement run() method. On calling start() method it will start a new thread.
Implement Runnable interface: We can implement java.lang.Runnable interface and pass the implemented object to the constructor of java.lang.Thread class. On calling start() it will start a new thread.

40. How can we stop a thread in the middle of execution in Java?
We can use a volatile variable as an indicator to stop the thread. We can create a volatile reference pointing to the current thread. This reference can be set to null by other threads to flag that the current thread should stop execution. In following example threadStopper is the volatile reference that can be set as null in stopThread() method by other threads.
Sample code is as follows:
public static class MyThread extends Thread {
private volatile Thread threadStopper;
public void start() {
threadStopper = new Thread(this);
threadStopper.start();}
public void stopThread() {threadStopper = null;}
public void run() {
Thread currThread = Thread.currentThread();
while(currThread == threadStopper) {
try {Thread.sleep(100);} catch (InterruptedException e) {}}}}

41. How do you access the current thread in a Java program?
We can access the current thread in Java by calling the static method currentThread() of java.lang.Thread class.
Sample code is as follows:
public class MyThread {
public static void main(String[] args) {// Get ID of Current Thread
long id = Thread.currentThread().getId();// Get Name of Current Thread
String name = Thread.currentThread().getName();}}

42. What is Busy waiting in Multithreading?
Busy waiting is also known as busy-looping or spinning. It is a multi-threading technique in which a process repeatedly checks if a condition is true. For example, a process can keep checking if any keyboard input is available. In general, busy waiting is considered as Anti-pattern that wastes processor time, so it should be avoided.
Sample code for busy waiting is as follows:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
long timeToStop = System.currentTimeMillis() + 1000;
long currentTime = System.currentTimeMillis();// Busy waiting
while (timeToStop > currentTime) {currentTime = System.currentTimeMillis();}}});

43. How can we prevent busy waiting in Java?
There is a simple way to prevent busy-waiting in Java. We can just put the current thread to sleep for given amount of time. It can be done by calling sleep() method of java.lang.Thread class. We can pass the number of milliseconds to sleep() method as an argument.

44. Can we use Thread.sleep() method for real-time processing in Java?
Java does not guarantee that Thread.sleep() will cause the thread to sleep for exactly N number of milliseconds. Sometime the thread can sleep for than N number of milliseconds. In real-time processing we need precise time period for which a thread should run or sleep. Therefore the invocation of Thread.sleep() method is not recommended for use in real-time processing.

45. Can we wake up a thread that has been put to sleep by using Thread.sleep() method?
We can use interrupt() method of java.lang.Thread class to interrupt a thread that is in sleep state. It will get InterruptedException to wake up from the sleep.
Sample code is as follows:
public class ThreadInterrupt implements Runnable {
public void run() {
try {Thread.sleep(Long.MAX_VALUE);} catch (InterruptedException e) {SOP(“Interrupted by exception!");}}
public static void main(String[] args) throws InterruptedException{
Thread myThread = new Thread(new ThreadInterrupt(),“myThread");
myThread.start();
SOP(“Sleeping in main thread for 10 seconds”);
Thread.sleep(10000);
SOP(“Interrupting myThread");
myThread.interrupt();}}

46. What are the two ways to check if a Thread has been interrupted?
These are the two ways to check for thread interruption:
In Java, a Thread can call Thread.interrupted() method to check if it has been interrupted or not.
The other option is to call isInterrupted() method of Thread class to check if it has been interrupted or not.

47.How can we make sure that Parent thread waits for termination of Child thread?
We can use join() method for this purpose. On calling join() method, current thread waits for the child thread to which it joins to finish.
Sample code is as follows:
Thread myThread = new Thread(new Runnable() {public void run() {}});
myThread.start();// Join on myThread
myThread.join();

48. How will you handle InterruptedException in Java?
In Java we can get InterruptedException from sleep() or join() methods. Throwing InterruptedException is way to inform that another thread has interrupted this thread. In general, the purpose of Interrupt is to ask current thread to stop its current execution and finish unexpectedly. Therefore ignoring this exception by catching it and only logging it to the console or some log file is not the recommended approach. The run() method of the Runnable interface does not allow that throwing any exceptions. So we cannot re-throw InterruptedException. Therefore the correct way to handle this exception is that run() method should check and handle this exception by itself and take appropriate action.

49. Which intrinsic lock is acquired by a synchronized method in Java?
When we mark a method as synchronized and then call this method, then this method will first acquire the intrinsic lock of the object in which that method is mentioned. Once the synchronized method returns, it releases the lock. In case the synchronized method throws an exception, the intrinsic lock will be released.
Sample code equivalent to a synchronized method is:
public void myMethod() {synchronized(this) {}}

50. Can we mark a constructor as synchronized in Java?
No. We cannot mark a constructor as synchronized. This will lead to compiler error. The reasoning behind this is that, in this case, only the constructing thread would have access to the object being constructed.

51. Do we have re-entrant property in intrinsic locks?
Yes. An intrinsic lock can be accessed by the same thread multiple times. So an Intrinsic lock is re-entrant. If it is not allowed then the code that acquires a lock would have to avoid acquiring the lock that it has already acquired.

52. What is an atomic operation?
An atomic operation is an operation that completes in a single step relative to other threads. An Atomic operation is either executed completely or not at all. There is no halfway mark in Atomic operation.

53. Can we consider the statement i++ as an atomic operation in Java?
No. The statement i++ is not an Atomic operation. It has more than one operation. First JVM loads the current value of i in memory. Then it increments it. Finally it stores the new value back into variable i. The current thread that executes this operation may be interrupted between any of the above-mentioned three steps. Therefore it is not an atomic operation.

54. What are the Atomic operations in Java?
Java language provides some basic Atomic operations. These operations can be used to make sure that concurrent threads always see the same value.
Some of these Atomic operations are:
Read operations on reference variables and primitive variables (except long and double)
Write operations on reference variables and primitive variables (except long and double)
Read operations on all variables declared as volatile
Write operations on all variables declared as volatile
55. Can you check if following code is thread-safe?
public class SingletonDoubleCheck {
private SingletonDoubleCheck instance = null;
public SingletonDoubleCheck getInstance() {if (instance == null) {synchronized (SingletonDoubleCheck.class) {if (instance == null) {instance = new SingletonDoubleCheck();}}}
return instance;
}}
The above-mentioned code is for creating a Singleton class. But this code is not thread-safe. In this we check the value of instance second time in the synchronized block. But the JIT compiler can rearrange the Bytecode in such a way that the reference to SingletonDoubleCheck instance will be set before the execution of constructor. Due to this the method getInstance() will return an object that may not have been initialized properly. We can use the keyword volatile for instance to make this threadsafe code. Any variables that is marked as volatile will be visible to other threads only after the completion of the constructor of the object.

56. Can we use primitive values for intrinsic locks?
No. Java does not allow primitive values to be used for intrinsic locks.



Comments

Popular posts from this blog

Microservices Interview Questions

Microservices Interview Questions 1. What is a Microservice in Java? A Microservice is a small and autonomous piece of code that does one thing very well. It is focused on doing well one specific task in a big system. It is also an autonomous entity that can be designed, developed and deployed independently. Generally, it is implemented as a REST service on HTTP protocol, with technology-agnostic APIs. Ideally, it does not share database with any other service. 2. What are the benefits of Microservices architecture? Microservices provide many benefits. Some of the key benefits are: 1.      Scaling : Since there are multiple Microservices instead of one monolith, it is easier to scale up the service that is being used more. Eg. Let say, you have a Product Lookup service and Product Buy service. The frequency of Product Lookup is much higher than Product Buy service. In this case, you can just scale up the Product Lookup service to run on powerful hardware with multipl

DOCKER Interview questions

DOCKER 1. What is Docker? Docker is Open Source software. It provides the automation of Linux application deployment in a software container. We can do operating system level virtualization on Linux with Docker. Docker can package software in a complete file system that contains software code, runtime environment, system tools, & libraries that are required to install and run the software on a server. 2. What is the difference between Docker image and Docker container? Docker container is simply an instance of Docker image. A Docker image is an immutable file, which is a snapshot of container. We create an image with build command. When we use run command, an Image will produce a container. In programming language, an Image is a Class and a Container is an instance of the class. 3. How will you remove an image from Docker? We can use docker rmi command to delete an image from our local system. Exact command is: % docker rmi <Image Id> If we want to fin

Cloud Computing Interview Questions

Cloud Computing 1. What are the benefits of Cloud Computing? There are ten main benefits of Cloud Computing: Flexibility : The businesses that have fluctuating bandwidth demands need the flexibility of Cloud Computing. If you need high bandwidth, you can scale up your cloud capacity. When you do not need high bandwidth, you can just scale down. There is no need to be tied into an inflexible fixed capacity infrastructure. Disaster Recovery : Cloud Computing provides robust backup and recovery solutions that are hosted in cloud. Due to this there is no need to spend extra resources on homegrown disaster recovery. It also saves time in setting up disaster recovery. Automatic Software Updates : Most of the Cloud providers give automatic software updates. This reduces the extra task of installing new software version and always catching up with the latest software installs. Low Capital Expenditure : In Cloud computing the model is Pay as you Go. This means there is very