Friday 6 June 2014

Thread(or Multithread) Interview Questions and Answers


1) What is Race Condition in Multithreading?

         A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.(This condition will arise in multi threading).

             So, let’s get into the actual problem. Let’s say that there’s a husband and wife - Ramesh and Savita - who share a joint account. They currently have Rs.2,000 in their account. They both log in to their online bank account at the same time, but from different locations.
They both decide to deposit Rs.500 each into their account through a wire transfer from other bank accounts that they have at the same time. So, the total account balance after these 2 deposits should be Rs.2,000 + (Rs.500 * 2), which equals Rs.3,000.
              Let’s say Ramesh’s transaction goes through first, but Ramesh's thread of execution is switched out (to Savita’s transaction thread) right after executing this line of code in the deposit method:

    updatedBalance = accountBalance + depositedAmount ;

Now, the processor is running the thread for Ramesh, who is also 
depositing Rs.500 into their account.  When Ramesh’s thread deposits Rs.500, 
the account balance is still only Rs2,000, because the variable accountBalance
 has not yet been updated in Savita’s thread.  Remember that Savita’s thread
 stopped execution right before the accountBalance variable was updated.

         So, Ramesh’s thread runs until it completes the deposit function, and then updates the value of the accountBalance variable to $2,500. After this, control returns to Savita’s thread, where updatedBalance has the value of Rs.2,500. Then, it just assigns this value of Rs.2,500 to accountBalance and returns. And that is the end of execution.
                 What is the result of these 2 deposits of Rs.500? Well, the accountBalance variable ends up being set to only Rs.2,500, when it should have been Rs.5,000. This means Ramesh and Savita lost Rs.500. This is good for the bank, but a huge problem for Ramesh and Savita, and any other of the bank's customers.

     To avoid Race Condition you can use Synchronization i.e lock one thread and access only one thread. If released the previous lock then second thread can access the resource.

2) What is difference between Thread and Prcoess in Java?

1) Both process and thread are independent path of execution but one process can have multiple threads.
2) Threads are called as a task or light weight process in operating system.
3)  Every process has its own memory space, executable code and unique process identifier while every thread has its own stack in java but it use to process main memory and share it with other threads.


3) Why Thread is faster compare to process?

         A thread is never faster than a process. If you run a thread(say there’s a process which has spawned only one thread) in one JVM and a process in another and that both of them require same resources then both of them would take same time to execute. But, when a program/Application is thread based(remember here there will be multiple threads running for a single process) then definitely a thread based application/program is faster than a process based application. This is because, when ever a process requires or waits for a resource CPU takes it out of the critical section and allocates the mutex to another process.
            Before De-allocating the earlier one, it stores the context(till what state did it execute that process) in registers. Now if this De-allocated process has to come back and execute as it has got the resource for which it was waiting, then it can’t go into critical section directly. CPU asks that process to follow scheduling algorithm. So this process has to wait again for its turn. While in the case of thread based application, the application is still with CPU only that thread which requires some resource goes out, but its co threads(of same process/application) are still in the critical section. Hence it directly comes back to the CPU and does not wait outside. Hence an application which is thread based is faster than an application which is process based.

            Be sure that its not the competition between thread and process, its between an application which is thread based or process based.

4)  What is Synchronization? Explain with example.

          Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multi threaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.

E.g. Synchronizing a function:
             public synchronized void Method1 () {
                      // Appropriate method-related code.
E.g. Synchronizing a block of code inside a function:
            public myFunction (){
                  synchronized (this) {
                         // Synchronized code here.

5)  Why wait,notify and notifyAll are in object class?

             Wait and notify is not just normal methods or synchronization utility,  more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized.
              Locks are made available on per Object basis, which is another reason wait and notify is
declared in Object class rather then Thread class.
              In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds lock instead they just know the lock is hold by some thread and
they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than thread in Java.

6) What is daemon thread in java?

         A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.
         When your program only have damon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.
         You can specify that a Thread is a daemon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops. 
Garbage Collection is a good example of  Daemon thread.

7)  What are the different states of Thread's life cycle ?

          There are five states of Thread's life cycle, as New, Runnable, Running, Blocked and Dead states. For more details please go through this link Explain Thread life cycle and difference between wait() and sleep() method

8)  What are the possible ways of creating Thread in Java?

      There are two possible ways to create thread in  Java. One is by extending java.lang.Thread class and other is by implementing Runnable interface. For more details, Please go through this link How many ways to create a thread in Java? Which one Prefer and why?

9) Once a thread has been started can it be started again?       

       No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been already started once an IllegalThreadStateException is thrown, which is a run time exception. A thread is in runnable state or dead thread can not be restarted.

10)  Which thread related methods are available in Object class?

       There are three thread related methods are available in Object class,
1) public final void wait() throws InterruptedException
2) public final void notify()
3) public final void notifyAll()

11) What is a volatile keyword? 

         In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile.

        The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

12) When jvm strats up, which thread will be started up first?

        When jvm starts up the thread executing main method is started. 

13) What will happen if we don't override the run() method of thread?

        When we call start() method on thread , internally it will call run() method to create the thread. If we don't override the run() method , won't be called and nothing will happen. 

           class MyThread extends Thread {
                       // don't override the run() method

           public class MainClass {

                    public static void main(String[] args) {
                             System.out.println("Main thread has started");
                             MyThread thread = new MyThread();
                             Sysstem.out.println("Main thread end");

output: Main thread has started
            Main thread end

14)  Producer Consumer Problem - Solution using wait and notify In Java 

For this question I have written separate post, go through this Producer and consumer solution using wait and notify


15) Producer Consumer Problem - Solution using BlockingQueue In Java 

For this question I have written separate post, go through this Producer and consumer solution using BlockingQueue

16)  What are the differences between Runnable and Callable interface in Java?    
    For this question I have written separate post, go through this  Difference between the Runnable and Callable interface in Java

17) Deadlock in Java multithreading - Program to generate the Deadlock and to avoid Deadlock in Java.

              In Java multi-threading, Deadlock is a situation where minimum two threads are holding lock on different resource and both are waiting for others resource to complete it's task. And both threads can hold lock forever and none of them complete it's task.  For details refer Program to generate deadlock in Java

18) Difference between Callable and Runnable interface in Java.

Refer Difference between Runnable and Callable interface.


  1. Good stuff.. Please add Concurret API questions

    1. Thanks Snehal, I will add soon. Thanks for visiting blog.