/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Threading Questions

Interview Questions on Thread in java

Interview Question's for fresher's (0-1)

Interview Question's Experienced

Interview Questions on Thread in java for Freshers (0-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.
When you execute something synchronously, you wait for it to finish before moving on to another task.
When you execute something asynchronously, you can move on to another task before it finishes.

What is a thread? What are the advantages we derived by programming with thread?

Threads allow programs to execute simultaneously. A thread is an independent path of execution in a program. These threads can be executed synchronously or asynchronously. All threads have a priority attached. Thread with a higher priority is executed first.
1. Allows multiple programs to be executed concurrently
2. Cost of thread is low compared to processes in terms of space and communication.
3. Threads are lightweight.

What are the benefits of multi-threaded programming?

In Multi-Threaded programming, multiple threads are executing concurrently that improves the performance because CPU is not idle incase some thread is waiting to get some resources. Multiple threads share the heap memory, so it’s good to create multiple threads to execute some task rather than creating multiple processes. For example, Servlets are better in performance than CGI because Servlet support multi-threading but CGI doesn’t.

Explain different way of using thread? ,Explain how to create a thread and start it running,

Java defines two ways in which this can be accomplished:
You can implement the Runnable interface.
You can extend the Thread class itself.
The Runnable is more advantageous, when you are going for multiple inheritance.

Read more - with example

Which one is better “implements Runnable” vs. “extends Thread” and Why ?

The most common difference is
When you extends Thread class , after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class). When you implements Runnable, you can save a space for your class to extend any other class in future or now.
However, the significant difference is. When you extends Thread class, each of your thread creates unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads.
When to use Runnable?
Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead. Performance Example of implement Runnable and extends Thread

When a thread is created and started, what is its initial state/different states of Thread in Java or ThreadLife-Cycle ?

The different states of threads are as follows:
1) 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.
2) 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.
3) 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.
4) 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.
5) Dead – 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.

What is the difference between preemptive scheduling and time slicing?

Thread Scheduler is the Operating System service that allocates the CPU time to the available runnable threads. Once we create and start a thread, it’s execution depends on the implementation of Thread Scheduler. Time Slicing is the process to divide the available CPU time to the available runnable threads.
Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time. Thread scheduling can’t be controlled by java, so it’s always better to control it from application itself.

What are differences between wait and sleep method in java?

sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.
wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.

What is the difference between yield() and sleep()?

yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.

What are the daemon threads?

Daemon thread are service provider threads run in the background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution.

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. E.g.

-: Syntex :-
public void synchronized method(){}  
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){
    // synchronized keyword on block of  code

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.

Can we call run() method of a Thread class?

Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, we need to start it using Thread.start() method.

What is context-switching in multi-threading?

Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. Context Switching is the essential feature for multitasking operating system and support for multi-threaded environment.

How can we make sure main() is the last thread to finish in Java Program?

We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function.

Example available here

How Thread communicate with each other

When threads share resources, communication between Threads is important to coordinate their efforts.

Object class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource.

Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block?

When a Thread calls wait() on any Object, it must have the monitor on the Object that it will leave and goes in wait state until any other thread call notify() on this Object.

Similarly when a thread calls notify() on any Object, it leaves the monitor on the Object and other waiting threads can get the monitor on the Object.

Since all these methods require Thread to have the Object monitor, that can be achieved only by synchronization, they need to be called from synchronized method or block.

What is ThreadLocal?

Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables. Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.

What is Thread Group? Why it’s advised not to use it?

ThreadGroup is a class which was intended to provide information about a thread group. ThreadGroup API is weak and it doesn’t have any functionality that is not provided by Thread. Two of the major feature it had are to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. But Java 1.5 has added setUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add uncaught exception handler to the thread. So ThreadGroup is obsolete and hence not advised to use anymore.

t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("exception occured:"+e.getMessage());

What is Deadlock? How to analyze and avoid deadlock situation?

Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources.
To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.
Avoid Nested Locks, Lock Only What is Required and Avoid waiting indefinitely are common ways to avoid deadlock situation, read this post to learn how to analyze deadlock in java with sample program.

What is synchronization in respect to multi-threading in Java?

With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program.

What is the difference between Thread.start() & Thread.run() method?

Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread.

If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.

Read more with example :- t.start() vs t.run()

Why do we need run() & start() method both. Can we achieve it with only run method?

We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.

What is ThreadLocal Class? How can it be used?

The java.lang.ThreadLocal class provides thread-local variables.
Below are some key points about ThreadLocal variables
1. A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
2. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
3. In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
4. 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)
For example, Spring, Spring Security and JSF each have the concept of a "Context" through which functionality of the framework is accessed. And in each case, that context is implemented both via dependency injection (the clean way) and as a ThreadLocal in cases where DI can't or won't be used.
It's bad for maintainability because it hides dependencies, and also directly causes problems because such containers use a thread pool.
Sometimes it also causes memory leaks.
Basically, it's a feature that can be very useful in a hackish way, but also very dangerous. I'd advise you to avoid it if possible.

When InvalidMonitorStateException is thrown? Why?

This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.

What is the difference between sleep(), suspend() and wait() ?

Thread.sleep() takes the current thread to a "Not Runnable" state for specified amount of time. The thread holds the monitors it has acquired. For example, if a thread is running a synchronized block or method and sleep method is called then no other thread will be able to enter this block or method. The sleeping thread can wake up when some other thread calls t.interrupt on it. Note that sleep is a static method, that means it always affects the current thread (the one executing sleep method). A common mistake is trying to call t2.sleep() where t2 is a different thread; even then, it is the current thread that will sleep, not the t2 thread. thread.suspend() is deprecated method. Its possible to send other threads into suspended state by making a suspend method call. In suspended state a thread keeps all its monitors and can not be interrupted. This may cause deadlocks therefore it has been deprecated. object.wait() call also takes the current thread into a "Not Runnable" state, just like sleep(), but with a slight change. Wait method is invoked on a lock object, not thread.
Here is the sequence of operations you can think
A thread T1 is already running a synchronized block with a lock on object - lets say "lockObject"
Another thread T2 comes to execute the synchronized block and find that its already acquired.
Now T2 calls lockObject.wait() method for waiting on lock to be release by T1 thread.
T1 thread finishes all its synchronized block work.
T1 thread calls lockObject.notifyAll() to notify all waiting threads that its done using the lock.
Since T2 thread is first in the queue of waiting it acquires the lock and starts processing.

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 two threads call two different synchronized instance methods of an Object?

No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed. See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods

What is a deadlock?

Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions: When two threads call Thread.join() on each other. When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

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 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:
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.
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. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. 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.

How to find a deadlock has occurred in Java? How to detect a Deadlock in Java?

Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.
findMonitorDeadlockedThreads() - This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor.
findDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.

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. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. 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.

What is a thread leak? What does it mean in Java?

Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang.

How can I trace whether the application has a thread leak?

If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways

Give unique and descriptive names to the threads created in application. - Add log entry in all thread at various entry and exit points in threads.

Change debugging config levels (debug, info, error etc) and analyze log messages.

When you find the class that is leaking out threads check how new threads are instantiated and how they're closed.

Make sure the thread is Guaranteed to close properly by doing following - Handling all Exceptions properly.

Make sure the thread is Guaranteed to close properly by doing following
Handling all Exceptions properly. releasing all resources (e.g. connections, files etc) before it closes.

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

Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.

You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).

Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.

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

Difference between a daemon thread and a low priority thread

Typically, daemon threads have nothing to do with priority. In Java, for example, the JVM shuts down when all user non-daemon threads finish. Marking a thread as a daemon thread means that it can be safely killed when the JVM exits.
Priority is about scheduling -- about how often a thread gets a time slice in comparison to other threads that are ready to run. You can have low priority daemon threads or high priority daemon threads. You can have non-daemon threads that are also low and high priority.
The concepts are orthogonal (mutually independent) -- at least in the Java thread model.
In terms of when to make a thread daemon, I use daemon threads for any tasks that I don't care if they are interrupted when the JVM quits: keep-alive threads, statistics processors, log handling, etc.. Everything mission critical to the application is a non-daemon thread that has to be specifically interrupted or signaled to quit somehow.

What is blocking Write code to implement blocking queue in Java?
Write code to solve the Produce consumer problem in Java?

A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full.

A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue.
A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more items or clearing the queue completely.

  -: Blocking Queue Implementation :-
public class BlockingQueue {

  private List queue = new LinkedList();
  private int  limit = 10;

  public BlockingQueue(int limit){
    this.limit = limit;

  public synchronized void enqueue(Object item)
  throws InterruptedException  {
    while(this.queue.size() == this.limit) {
    if(this.queue.size() == 0) {

  public synchronized Object dequeue()
  throws InterruptedException{
    while(this.queue.size() == 0){
    if(this.queue.size() == this.limit){

    return this.queue.remove(0);


Notice how notifyAll() is only called from enqueue() and dequeue() if the queue size is equal to the size bounds (0 or limit).
If the queue size is not equal to either bound when enqueue() or dequeue() is called, there can be no threads waiting to either enqueue or dequeue items.

Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?

Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized. Below is the example which demonstrates this, The Common class has two methods synchronizedMethod1() and method1() MyThread class is calling both the methods in separate threads,