Tuesday 14 February 2017

Multithreading Interview Questions

1) What is the difference between Process and Thread? A process is a self contained execution environment and it can be seen as a program... thumbnail 1 summary
1) What is the difference between Process and Thread?

A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

2) What is Multithreading in Java ?

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

3) What are the different ways of creating thread?

Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution.
public class NewThread extends Thread{
  public void run(){ 
    // the code that has to be executed in a separate new thread goes here
    } 
    public static void main(String [] args){ 
    NewThread c = new NewThread(); 
    c.start(); 
  }              
}

Implements the Runnable interface.The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created.
public class NewThread implements Runnable{
  public void run(){ 
  // the code that has to be executed in a separate new thread goes here
    } 
  public static void main(String [] args){ 
     NewThread c = new NewThread(); 
     Thread t = new Thread(c);
     t.start();
    }
}

4) What is Life cycle of a Thread (Thread States)?

The different states of threads are as follows:

New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked.
Terminated – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

5) What is use of synchronized keyword?

Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition.
public void synchronized method(){} 
  public void synchronized staticmethod(){}
  public void myMethod(){
     synchronized (this){ 
        //synchronized keyword on block of code
     }
  }

6) What is Static synchronization & non static synchronization?

A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object.
If you make any static method as synchronized, the lock will be on the class not on object.

7) 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.

8) Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

9) Why wait(), notify(), notifyAll() must be called inside a synchronized method/block?

We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java.
One thread is waiting after checking a condition e.g. In the classic Producer-Consumer problem, the Producer thread waits if the buffer is full and Consumer thread notify Producer thread after it creates a space in the buffer by consuming an element.

Calling notify() or notifyAll() methods issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block, all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further. Read More....

10) What is ThreadLocal variables? How can it be used?

Below are some key points about ThreadLocal variables

  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
11) What is the difference between yield() and sleep()?

yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. If doesn't release the lock on the objects acquired.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t releases the lock.

12) What is the difference between wait() and sleep()?

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution

13) What is join() method?

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

14) Is it possible to start a thread twice?

No, there is no possibility to start a thread twice. If you does so, an IllegalThreadStateException is thrown.

No comments

Post a Comment