Showing posts with label multitasking. Show all posts
Showing posts with label multitasking. Show all posts

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.


PROCESSTHREAD
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 ?
ADVANTAGES 
  • 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. 
DISADVANTAGES                     
  • 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:

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

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

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

WAITING
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

TIMED_WAITING
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

TERMINATED
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?
YES.

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

Saturday, September 21, 2013

Intrinsic Locks and Synchronization

What is Synchronization ?
Synchronization is a way to control the access to a shared resource in multithreaded environment in such a way that only one thread can access a shared resource at a time. Synchronization is achieved through the concept of monitor. A monitor is an exclusive lock that is obtained on an object by a thread when a synchronized method is called on the object ( or a synchronized block is executed ). 


Intrinsic lock / Monitor lock.
Intrinsic lock or monitor lock plays an important role in different aspects of synchronization :
  • It enforces exclusive access to object's state .
  • It establishes Happens-before relationship that is essential for visibility .

Syntax.
synchronized keyword is used to denote that a particular block of code is to be executed in a monitor. Synchronization can be done in two ways :

1. Synchronized methods .
synchronized keyword can be used with both instance methods and static methods .
// Synchronizing instance methods . Lock will be taken on the current object i.e object used to call the method doStuff().
public synchronized void doStuff(){
    // Statements to be executed in monitor.
}

// Synchronizing static methods . Lock will be taken on class instance ( java.lang.Class ) 
public static synchronized void doSomeExtra(){
    // Statements to be executed in monitor.
}


2. Synchronized statements.

It is useful for improving concurrency with fine grained synchronization.

// Synchronizing blocks . Lock will be taken on the current object i.e object used to call the method doStuff().
public void doStuff(){
    // Statements that are not executed in monitor.
    synchronized(this){
    // Statements to be executed in monitor.
    }
}

Reentrant synchronization 
Allowing a thread to acquire a lock more than once is called Reentrant synchronization. This can happen in a scenario where one synchronized code , directly or indirectly invokes a method that also contains synchronized code , and both the code use the same lock . Without reentrant synchronization , synchronized code would have to take many additional precautions to avoid having a thread cause itself to block . 

Limitations of Synchronization 
Synchronization can only make sure that a shared object can be accessed by one thread at a time . It can not determine order of the usage . Sometimes there is a need to use a common resource in a specific order by multiple threads .

Thursday, August 15, 2013

Understanding Threads in Java

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

main() method is executed as a Thread.
When an application ( or a program ) is run, a user thread is created to execute the main() method of the application. This thread is called main thread.

Thread Creation :
A thread in java is represented by an object of class java.lang.Thread and can be created in two ways :

1. Implementing java.lang.Runnable interface.
The Runnable interface defines a method run() that contains the code that is to be executed in a thread. Lets create a thread that says " Hello User ".

public class MyRunnable implements Runnable {

 // Statements defined in run() methods are executed as a thread.
 public void run(){
  System.out.println("Hello User");
 }

 public static void main(String[] args) {             
  // Creating an object of Thread class and passing a Runnable in its constructor.
  Thread thread = new Thread(new MyRunnable());

  // Starting a thread.
  thread.start();
 }
}
 
    
2. Extending java.lang.Thread class.
Another way to create a thread is by extending Thread class  and override the run() method .The Thread class itself implements Runnable but its run() method does nothing.

public class MyThread extends Thread {

 public void run() {
  System.out.println("Hello User");
 }

 public static void main(String[] args) {
  new MyThread().start();
 }
}

What is Multitasking ?

Multitasking is the ability to perform more than one activity concurrently on a computer. We can further break multitasking into process based and thread based .

Process-based Multitasking 
Process-based multitasking allows processes ( or programs ) to run concurrently on a computer. For example , running different applications at the same time like downloading a file and printing a file .

A process has a self-contained execution environment. A process has a complete , private set of basic resources . Each process has its own memory space.

Thread-based Multitasking
Thread-based multitasking allows different parts of the same process ( program ) to run concurrently .
A good example is printing and formatting text in a word processor at the same time.
Thread-based multitasking is only feasible if the two parts are independent of each other or more precisely they are independent paths of execution at run time.

Threads are also referred as lightweight processes and they also provide an execution environment . Threads exists within a processes and share its resources like memory and open files.

We have several advantages of Thread-based multitasking over Process-based multitasking .

1. Threads shares the same address space.

2. Context switching between the threads is less expensive than in Processes.