Thursday, February 20, 2014

20 basic Multithreading Interview Questions

Hi.  This post dedicated to some basic questions on Java multithreading concepts.
Multithreading is a topic that is asked in all the interviews, and  especially in companies working on banking solutions .

1. What is a Thread?

Thread is an independent sequential path of execution within a process / program. Multiple threads can run concurrently in a program . Threads are lightweight as compared to the process as at runtime , they exist in a common memory space and can share process's resources like  data and code.

Threads make the runtime environment asynchronous , allowing different tasks to be performed concurrently . In Java , a thread is represented and controlled by an object of class java.lang.Thread.

To know what is multitasking , see  What is Multitasking .
To know more about thread creation using Runnable interface and Thread class , See Understanding Threads in Java

2. What is thread priority ? How can we set the priority of a thread ?
Thread scheduler schedules the threads based on their priority relative to other Runnable threads . A newly created java thread has the same priority as the thread which created it .
Thread priority is an int number whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread.

setPriority method can be used to set the thread priority .

3. What is the difference between Thread and Process?
The table mentioned below lists the differences between a Process and Thread.

A Process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources. Each process has its own memory space. For example : When we start Microsoft word , a new process is created .A Thread is also an execution environment , but is lightweight as compared to a process . Thread is also called a "lightweight process". Thread exists within a process and shares the processes's resources , including memory and open files.
Different Processes have separate address spaces .Threads share the address space of its process.
Context-switching between the process is slower.Context-switching between threads in same process is comparatively faster.
processes interact only through system-provided inter-process communication mechanismsThreads can easily communicate within a process.

4. What are the advantages and Disadvantages of using threads ?
  • Better use of system resources.
  • Parallelization of tasks . Threads supports concurrent operations . For example multiple requests can be processed simultaneously by different threads.
  • Enhanced performance on multi-processor machines.
  • Provides better availability in GUI applications. 
  • Increases the overall complexity of the system . Multithreaded applications are difficult to debug , sometimes gives  unpredictable results.
  • Need to synchronize the shared resources ( Objects ) to maintain their state. 
  • Multithreading can result in potential deadlock situations.
  • Some threads may not get proper time to run ( Starvation ) . 

5. What are the different ways of creating a thread?
Threads can be created in two ways :
  • Extending Thread class.
  • Implementing Runnable interface.
For more details see Understanding Threads in Java.

6. What are the different states in thread's life cycle?
A thread can be in one of the following states:

A newly instantiated thread that has not yet started  is in NEW state.

A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.

A thread that is blocked waiting for a monitor lock is in this state.The thread enters in this state after calling Object.wait

A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
The thread enters into this state after calling one of these :
  • Object.wait with no timeout
  • Thread.join with no timeout
  • LockSupport.park

A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
The thread enters into this state after calling one of these methods with a specified time :
  • Thread.sleep
  • Object.wait with timeout
  • Thread.join with timeout
  • LockSupport.parkNanos
  • LockSupport.parkUntil

A thread that has completed its execution is in this state.

7.What is the use of synchronized keyword?
synchronized keyword is used to control the access of multiple threads on a shared resource . synchronized keyword can be used with both static and instance methods.
It can also be used with a block of code. 

// synchronized keyword on non static method.
public void synchronized doStuff(){}  

// synchronized keyword on static method.
public  static void synchronized doStuff(){}

public void doStuff(){
            synchronized (this){        
                   // synchronized keyword on block of  code

To get more idea of Synchronization , see Intrinsic locks and Synchronization.

8. Can we use synchronized keyword with classes and variables ?
NO. Only methods can be synchronized.

9. Can a class contain both synchronized and non-synchronized methods?

10. What is the difference when the synchronized keyword is applied to a static method and  a non static method?
When a non static synchronized method is called , lock is taken on the current instance , i.e the one that is used to call the method where as for synchronized static method , lock is taken on the class.

11. What is a volatile keyword?
volatile keyword indicates the compiler not to cache the value of a field and always read it from the main memory . The volatile keyword  guarantees that -
  • Any thread accessing a volatile field will read its current value from main memory before continuing , instead of using a cached value.                                                                
  • Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a lock . 

12. What is the difference between yield() and sleep() methods ?

yield() allows the current running thread to release the lock so that other threads of same priority can acquire the lock . yield is only a hint to the scheduler and scheduler is totally free to ignore it .

public static void yield()

sleep() method causes the currently executing thread to sleep for a specified period of time ( in milliseconds ) . The thread doesn't release the lock.

public static void sleep(long millis) throws InterruptedException

public static void sleep(long millis,int nanos) throws InterruptedException

13. What is the difference between wait() and sleep()?
wait() method is defined in Object class whereas  sleep()  method is defined in Thread class.

wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object . Thread releases the lock as soon as the wait is called .  sleep() method causes the currently executing thread to sleep for a specified period of time ( in milliseconds ) . The thread doesn't release the lock.

14. What is difference between notify() and notifyAll()?
notify() method wakes up a single thread that is waiting on this object's monitor. There might be several threads waiting for this object and only one of them is chosen.
On the other hand , notifyAll() method wakes up all threads that are waiting on this object's monitor. 

Also see , Inter thread communication using notifyAll() method.

15. What happens if run method is directly invoked?
Calling the start() method creates a new thread of execution . It means new thread is created by the JVM and the statements defined in the run method is executed in the newly spawned thread  . By calling the run() method directly , the same will be executed in the caller's thread and not in  the new thread . 

16.  What happens when start() is called?
A new thread of execution with a new call stack starts . The state of thread changes from NEW to RUNNABLE . JVM calls the run method of this thread .

17.  Can a start() method be called multiple times on a Thread ?
It is not legal to start a thread more than once and therefore start() method can only be called once on a thread . 

18 . Can a thread be restarted after completing its execution ?
NO . A thread may not be restarted once it has completed execution.

19.  What is the priority of a newly created thread ?
The priority of a newly created thread is equal to the priority of the thread which has created it .

20. What is daemon thread?
There are basically two type of threads : User threads and Daemon threads . Daemon threads are service provider threads that run in the background .JVM does not wait for the daemon threads to complete their execution if all user threads have completed their execution.

A good example is Garbage Collector , which is a daemon thread and is used to reclaim the unused memory . 

Thread class provides a method  to make a thread daemon -
public void setDaemon(boolean status)

To check if a thread is daemon - 
public boolean isDaemon()

Related Tutorials :

What is Multitasking ?    
Understanding Threads in Java
Thread interference and Memory consistency errors       
Race condition in Concurrency            
Immutable object in java          
Intrinsic Locks and Synchronization  
Inter thread communication showing the usage of notifyAll() method

1 comment :

  1. Indeed very good question, By the way I have recently some 50 thread questions form Java Interviews, you guys may find it useful.