Java Interview Questions - MultiThreading

This set of Java Interview Questions covers MultiThreading topics like Threads, Synchronization, DeadLock, Thread Pool and more.

You can find the previous set of Interview Questions from here:

1. What is the difference between processes and threads?
A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.
2. Explain different ways of creating a thread? Which one is preferred?
Threads can be used by either
  • Extending the Thread class.
    class Counter extends Thread {
        
        //method where the thread execution will start
        public void run(){
            //logic to execute in a thread   
        }
     
        //let’s see how to start the threads
        public static void main(String[] args){
           Thread t1 = new Counter();
           Thread t2 = new Counter();
           t1.start();  //start the first thread.
           t2.start(); //this starts the 2nd thread.
        }
    }
  • Implementing the Runnable interface.
    class Counter extends Base implements Runnable{
       
        //method where the thread execution will start
        public void run(){
            //logic to execute in a thread   
        }
     
        //let us see how to start the threads
        public static void main(String[] args){
             Thread t1 = new Thread(new Counter());
             Thread t2 = new Thread(new Counter());
             t1.start();  //start the first thread.
             t2.start();  //this starts the 2nd thread.
        }
    }
The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you.
3. Briefly explain high-level thread states?
A Thread can have the below states:
  1. Runnable: A thread becomes runnable when you call the start( ), but does not necessarily start running immediately. It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
  2. Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently
  3. Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokes currObject.notify( ) or the currObject.notifyAll( ) is executed.
  4. Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  5. Blocked :Will move to runnable after chnage in I/O condition or when lock is acquired.
  6. Dead: The thread is finished working.
4. What is multithreading and what are the methods for inter-thread communication?
Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class.
  • wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state.
  • notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
5. What's the difference between the methods sleep() and wait()?
  • The code sleep(1000); puts thread aside for exactly one second whereas the code wait(1000), causes a wait of up to one second.
  • A thread could stop waiting earlier if it receives the notify() or notifyAll() call.
  • The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
6. Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?
Every Java Object has a monitor associated with it. The threads using that object can lock or unlock the monitor associated with the object. Wait and notify/notifyAll methods are responsible for acquiring and relinquishing the lock associated with the particular object. Calling wait causes the current thread to wait to acquire the lock of the Object, and calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.
7. What do you understand by Synchronization?
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 multithreaded 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.
  }
}
8. What are the disadvantages of synchronization?
The disadvantage of synchronize is it will end up in slowing down the program. Also if not handled properly it will end up in dead lock.
9. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
10. When you will synchronize a piece of your code?
When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
11. What is a ThreadLocal class?
ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads.
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)
12. What is deadlock?
When two threads are waiting each other and can’t precede the program is said to be deadlock. Deadlock may occur when two threads, each having a lock on the same resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other resource to release the lock, unless one of the user processes is terminated.
The thread deadlock can occur in conditions such as:
  1. two threads calling Thread.join() on each other.
  2. two threads use nested synchronized blocks to lock two objects and blocks lock the same objects in different order.
13. What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
14. What is immutable object? How does it help in writing concurrent application?
An object is considered immutable if its state cannot change after it is constructed. Immutable objects are particularly useful in concurrent applications, since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your multi threaded program, since they are
  • Simple to construct, test, and use.
  • Automatically thread-safe and have no synchronization issues.
To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
15. What is Starvation? and What is a Livelock?
Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.
  • LiveLock : Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
    1. When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
    2. When all the threads in a program are stuck in infinite loops.
  • Starvation : Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.
16. What is thread pool? Why should we use thread pools?
A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment.
One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread.
Below are key reasons to use a Thread Pool :
  1. Using thread pools minimizes the JVM overhead due to thread creation.
  2. You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).

1 comments:

Related Posts Plugin for WordPress, Blogger...
 

Copyright © 2012 | ScriptSplash | Powered by Blogger Templates