October 01, 2016

Java Thread Interview Questions & Answers..

What is Thread in Java?
Thread in Java is a light weight process and represent an independent path of execution. It's way to take advantage of multiple CPU available in a machine. By employing multiple threads you can speed up CPU bound task.

E.g, if one thread takes 100 milliseconds to do a job, you can use 10 thread to reduce that task into 10 milliseconds. Java provides excellent support for multithreading at the language level, and it's also one of the strong selling points.

What is the difference between Thread and Process in Java?

  • One process can contain multiple threads, which means the thread is a subset of Process.
  • Two process runs on different memory space, but all threads share same memory space. Don't confuse this with stack memory, which is different for the different thread and used to store local data to that thread. 
  • Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes. 

What is a daemon thread?
Daemon threads are sometimes reffered as "service" threads. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. e.g: a daemon thread is provided by JVM, which is continuously running is the garbage collector thread.

How do you implement Thread in Java?
There are two ways of implementing threading in Java :
1) By extending java.lang.Thread class
2) By implementing java.lang.Runnable interface

Since Thread class itself implement Runnable, we can override run() method either by extending Thread class or just implementing Runnable interface.

1).
public class MyThread extends Thread{
   public void run(){
      System.out.println("My Thread Running: " + Thread.currentThread().getName());
   }
 }
....
....
Thread mythread = new MyThread();
mythread.setName("mythread");
mythread.start();


2).
public class MyRunnable implements Runnable{        
public void run(){
       System.out.println("My Runnable Running: " + Thread.currentThread().getName());
    }
}

....
.....
//An instance of java.lang.Thread represent a thread but it needs a task to execute, which is an instance of interface java.lang.Runnable.
Thread myrunnable = new Thread(new MyRunnable(),"mythreadwithrunnable");
myrunnable.start();


What is the difference between start() and run() method of Thread class?
When a program calls start() method, a new Thread is created and code inside run() method is executed in new Thread. If you call run() method directly, no new Thread will be created and code inside run() will be executed on current Thread.

Another difference between start vs run in Java thread is that you can not call start() method twice on thread object. Once started, second call of start() will throw IllegalStateException in Java while you can call run() method twice.

What is the difference between Runnable and Callable in Java?
1. Runnable is there from JDK 1.0 while Callable was added on JDK 1.5.
2. Runnable interface has run() method to define task while Callable interface uses call() method for task definition.
3. run() method does not return any value, it's return type is void while call method returns  java.lang.Object type. The Callable interface is a generic parameterized interface and Type of value is provided when an instance of Callable implementation is created.
4. One more difference is that the Callable interface can throw checked exception, while Runnable can't [run() does not throw any checked exception)

What is the difference between CyclicBarrier and CountDownLatch in Java?
The main difference between CountDownLatch & CyclicBarrier is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. (For more info read : Difference between CountDownLatch & CyclicBarrier in Java)

What is volatile variable in Java?
volatile variable in Java is a special variable which is used to signal threads, a compiler that this particular variables value are going to be updated by multiple threads inside Java application.

When we make a variable, we ensures that its value should always be read from main memory and thread should not use cached value of that variable from their own stack.

The volatile keyword can only be applied to a variable, it can not be applied to class or method. using volatile keyword along with class and method is a compiler error.

When to use Volatile variable in Java?
1) Any variable which is shared between multiple threads should be made variable, in order to ensure that all thread must see the latest value of the volatile variable.
2) A signal to compiler and JIT to ensure that compiler does not change ordering or volatile variable and moves them out of synchronized context.
3) You want to save the cost of synchronization as volatile variables are less expensive than synchronization.

What is race condition in Java?
Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other.

It is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled.

Race conditions can lead to unpredictable results and subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.

A race condition occurs due to race between multiple threads, if a thread which is supposed to execute first lost the race and executed second, behaviour of code changes, which surface as non-deterministic bugs. This is one of the hardest bugs to find and re-produce because of random nature of racing between threads.

How to stop a thread in Java?
It's easy to start a thread in Java because you have a start() method, but it's difficult to stop the thread because there is no working stop() method. There was some control methods in JDK 1.0 e.g. stop(), suspend() and resume() which was deprecated in later releases due to potential deadlock threats

Programmers mainly rely on the fact that thread stops automatically as soon as they finish execution of run() or call() method. To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks. e.g:

class Server implements Runnable{
    private volatile boolean isforexit = false;   
    public void run() {
        while(!isforexit){
            System.out.println("Server is running!!");
        }       
        System.out.println("Server is stopped!!");
    }   
    public void stop(){
        isforexit = true;
    }
}
public class MyThreadStopTest {
    public static void main(String args[]) throws InterruptedException {
        Server myServer = new Server();

        Thread t1 = new Thread(myServer, "T1");
        t1.start();
        myServer.stop();       
        TimeUnit.MILLISECONDS.sleep(200);
    }
}


What happens when an Exception occurs in a thread?
If exception is not caught thread will die, else if an uncaught exception handler is registered then it will get a call back.

What is the use of Thread.UncaughtExceptionHandler interface?
Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.

As we know, Checked exceptions must be specified in the throws clause of a method or caught inside them. Where as, Unchecked exceptions don’t have to be specified or caught.

When a checked exception is thrown inside the run() method of a Thread object, we have to catch and treat it accordingly, because the run() method doesn’t accept a throws clause. But when an unchecked exception is thrown inside the run() method of a Thread object, the default behavior is to write the stack trace in the console (or log it inside error log file) and exit the program.

However, with UncaughtExceptionHandler interface, Java provides us with a mechanism to catch and treat the unchecked exceptions thrown in a Thread object to avoid the program ending.

When a thread is about to terminate due to an uncaught exception, the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.

E.g:
1). You need to implement UncaughtExceptionHandler:
class MyExceptionHandler implements UncaughtExceptionHandler
{
   public void uncaughtException(Thread t, Throwable e)
   {
      System.out.printf("An exception has been captured. Thread: %s\n", t.getId());
      System.out.printf("Exception: %s: %s\n", e.getClass().getName(), e.getMessage());
      System.out.printf("Stack Trace: \n");
      e.printStackTrace(System.out);
      System.out.printf("Thread status: %s\n", t.getState());
      new Thread(new Task()).start();
   }
}

2). Set UncaughtExceptionHandler inside run() method:
class Task implements Runnable
{
   @Override
   public void run()
   {
      Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
      .....
   }
}


What are the different states of a thread's lifecycle?
  • Runnable:waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
  • 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.
  • Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
  • Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  • Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
  • Blocked on synchronization: Will move to Runnable when a lock is acquired.
  • Dead: The thread is finished working.
What is the difference between yield and sleeping?
Both yield and sleep are declared on java.lang.Thread class and doesn't release any lock held by the thread.

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.

sleep() allows the thread to go to sleep state for x milliseconds.

When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.

How do you share data between two thread in Java?
wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object.

Classical example of wait and notify method is Producer Consumer design pattern, where One thread produce and put something on shared bucket, and then tell other thread that there is an item for your interest in shared object, consumer thread than pick than item and do his job, without wait() and notify(), consumer thread needs to be busy checking, even if there is no change in state of shared object.

This brings an interesting point on using wait and notify mechanism, a call to notify() happens, when thread changed state of shared object i.e. in this case producer change bucket from empty to not empty, and consumer change state from non-empty to empty.

Also wait and notify method must be called from synchronized context. A waiting thread may woke up, without any change in it's waiting condition due to spurious wake up. e.g: if a consumer thread, which is waiting because shared queue is empty, gets wake up due to a false alarm and try to get something from queue without further checking whether queue is empty or not than unexpected result is possible.

What is the difference between notify and notifyAll in Java?
notify will only notify one Thread and notifyAll method will notify all Threads  which are waiting on that monitor or lock.

When you call notify only one of waiting for the thread will be woken and it's not guaranteed which thread will be woken, it depends on upon Thread scheduler.

While if you call notifyAll method, all threads waiting on that lock will be woken up, but again all woken thread will fight for lock before executing remaining code. That's why wait is called on loop because if multiple threads are woken up, the thread which will get lock will first execute and it may reset waiting for condition, which will force subsequent threads to wait.

Why wait, notify and notifyAll are not inside thread class? 
Java provides lock at object level not at thread level thats why wait, notify and notifyAll methods are defined in Object class. Every object has lock, which is acquired by thread. Now if thread needs to wait for certain lock it make sense to call wait() on that object rather than on that thread.

Had wait() method declared on Thread class, it was not clear that for which lock thread was waiting. In short, since wait, notify and notifyAll operate at lock level, it make sense to defined it on object class because lock belongs to object.

Why wait and notify method are called from synchronized block?

Every object created in Java has one associated monitor (mutually exclusive lock). Only one thread can own a monitor at any given time.

For achieving synchronization in Java this monitor is used. When any thread enters a synchronized method/block it acquires the lock on the specified object. When any thread acquires a lock it is said to have entered the monitor. All other threads which need to execute the same shared piece of code (locked monitor) will be suspended until the thread which initially acquired the lock releases it.

wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to waiting state.

notify method wakes up a single thread that is waiting on this object's monitor, where as notifyAll method wakes up all the threads that called wait( ) on the same object.

Any method or a block of code, if not qualified with the keyword synchronized can be executed by more than one thread at any given time as object's monitor(lock) is not in the picture. Where as when a method is synchronized (or there is a synchronized block) only a single thread who has acquired the object's monitor can access the code.

Since wait method is about thread releasing the object's lock and go to waiting state, where as notify/notifyAll methods are about notifying the thread(s) waiting for the object's lock. So, wait(), notify() and notifyAll() methods (as mentioned above) should be invoked on an object only when the current thread has already acquired the lock on an object.

If you don't call them from synchronized context, your code will throw IllegalMonitorStateException. A more subtle reason is to avoid the race condition between wait and notify calls.

What is the difference between the interrupted() and isInterrupted() method in Java?
In simple words, if you use interrupted, you're asking "Have I been interrupted since the last time I asked?". Where as isInterrupted tells you whether the thread you call it on is currently interrupted.

The interrupted() method is a class (static) method that always checks the current thread and clears the interruption flag. A second call to interrupted() will return false.

The isInterrupted() method is an instance method, it reports the status of the thread on which it is invoked. Also, it does not clear the interruption flag. If the flag is set, it will remain set after calling this method.

What is the difference between wait() and sleep()?
  • The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.
  • The wait() method can only be called from Synchronized context i.e. using synchronized block or synchronized method. The sleep() method can be called from any context.
  • The wait() method releases the lock on an object and gives others chance to execute. The sleep() method does not releases the lock of an object for specified time or until interrupt.
  • A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be awaked by interrupt or time expires.

What is thread pool?
We all know, creating a thread is expensive in terms of time and resource. If we create thread at time of request processing it will slow down our response time, also there is only a limited number of threads a process can create.

A Thread Pool gives us an option to avoid these issues. When a application starts-up, a pool of threads are created and the threads are reused for request processing. This pool of thread is known as 'thread pool' and threads are known as 'worker thread'.

From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of threads) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks).

How do you check if a Thread holds a lock or not?
holdsLock() method from java.lang.Thread, it returns true if and only if the current thread holds the monitor lock on the specified object.

What is use of synchronized keyword?
Synchronized keyword provides a lock on the object and thus prevents race condition and 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. 

What happens when I make a static method as synchronized?
Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.

Can we synchronize the run method? If yes then what will be the behavior?
Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object.

Can we synchronize the constructor of a Java Class?
As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish.

What is busy spin in a multi-threaded environment? or What is Busy Spinning?
It is one of the interesting multithreading question for senior Java programmers.

Busy spinning is a waiting strategy, in which one thread repeatedly checks to see if a condition is true instead of calling wait or sleep method and releasing CPU. It simply eats up the computer cycle because one thread keeps on looping continuously waiting for another thread to signal.

By not releasing the CPU or suspending the thread, your thread retains all the cached data and instruction, which may be lost if the thread was suspended and resumed back in a different core of CPU.

e.g:
while(isAllowedToProcess){
  System.out.println("waiting!! waiting!!");
}


What is ThreadLocal variable in Java?
Like instance variable is per instance, ThreadLocal variable is per thread. Since class is expensive, its not good to use it in local scope, which requires separate instance on each invocation.

What is thread pool?
We all know, creating a thread is expensive in terms of time and resource. If we create thread at time of request processing it will slow down our response time, also there is only a limited number of threads a process can create.

A Thread Pool gives us an option to avoid these issues. When a application starts-up, a pool of threads are created and the threads are reused for request processing. This pool of thread is known as 'thread pool' and threads are known as 'worker thread'.

What is the Java Thread Executor Framework?
Executor Framework in java has been introduced in JDK 5. It handles creation of thread, creating the thread pool and checking health while running and also terminates if needed.

Java API provides Executor framework, which allows you to create three different types of thread pools:
1.Executor.newCachedThreadPool: Creates a thread pool of unlimited size, but if threads get freed up, they are reused
2.Executor.newFixedThreadPool: Create a thread pool of fixed size, if pool is exhausted, tasks must wait till a thread becomes free
3.Executor.newSingleThreadExecutor: Creates only a single thread, tasks are executed sequentially form the queue

How to terminate a thread in Executor Framework in java?
When you are done using the ExecutorService you should shut it down, so the threads do not keep running.

e.g, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExexutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.

To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.

If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

What is the role of Executors.unconfigurableExecutorService in Executor Framework?
The unconfigurableExecutorService method in java executor returns an object that delegates all methods of ExecutorService to the given executor so that any other method cannot accessed by cast.

What is the role of ExecutorService in Java?
The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool. In fact, the implementation of ExecutorService present in the java.util.concurrent package is a thread pool implementation. e.g:

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});
executorService.shutdown();


First an ExecutorService is created using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.

Second, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService

What is the role of FutureTask and Future in java?

FutureTask is base concrete implementation of Future interface and provides asynchronous processing. It contains the methods to start and cancel a task and also methods that can return the state of the FutureTask as whether it’s completed or cancelled.

We need a callable object to create a future task and then we can use Java Thread Pool Executor to process these asynchronously.

A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.
How to use Callable and Future in Java?
The run() method of Runnable interface does not return any value, so if you need to get a value back from the now-completed task, you must use a method outside the interface and wait for some kind of notification message that the task completed. e.g:
Runnable runnable = ...;
Thread t = new Thread(runnable);
t.start();
t.join();
String outValue = callMethodToGetTheValue();

With Callable interface (which was introduced in J2SE 5.0) we can get the value by calling call() method. The call() can return an Object or, more specifically, any type that is introduced in the generalized form.

public interface Callable< V  >   {
     V call() throws Exception;
}


We cannot pass a Callable into a Thread to execute, instead ExecutorService is used to execute the Callable object. The service accepts Callable objects to run by way of the submit() method:

< T  >   Future< T  >   submit(Callable< T  >   task)

As the method definition shows, submitting a Callable object to the ExecutorService returns a Future object. The get() method of Future will then block until the task is completed. This is the equivalent of the join() call. Actually, it is the equivalent of both the join() call and the get value call as get() returns the value calculated by the Callable instance.

import java.util.*;
import java.util.concurrent.*;
public class CallableTest {

public static class WordLengthCallable implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
}

public static void main(String args[]) throws Exception {
    String[] strArray = new String[2];
    strArray[0] = "Mariam";
    strArray[1] = "Donald";
   
    ExecutorService pool = Executors.newFixedThreadPool(3); // Executors.newSingleThreadExecutor();
    Set< Future< Integer  >    >   set = new HashSet< Future< Integer  >    >  ();
    for (String word: strArray) {
      Callable< Integer  >   callable = new WordLengthCallable(word);
      Future< Integer  >   future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future< Integer  >   future : set) {
      sum += future.get();
    }
    System.out.print("The sum of lengths is :"+ sum);
  }
}


-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory