Top Interview Questions & Answers | Learn Now

Thread Interview Questions and Answers

Written by Bhavya Sri | Mar 29, 2018 5:40:11 AM

Q1. What is a meant by Thread?

Ans: In Java, 'thread' means two different things:

  1. An instance of class java.lang.Thread.
  2. A thread of an execution.

An instance of Thread is just an object. Like any other object in Java, it has variables and methods and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack or to think of it in reverse, one call stack per thread. Even if you don't create any new threads in your program, threads back there are running.

Q2. What is the difference between a thread and a process?

Ans:


  • Threads share the address space of the process that created it whereas processes have their own address.
  • Threads have direct access to the data segment of its process while processes have their own copy of the data segment of the parent process.
  • Threads can directly communicate with other threads of its process while on the other hand processes must use interprocess communication to communicate with sibling processes.
  • Threads have almost no overhead while processes have considerable overhead.
  • New threads are easily created whereas new processes require duplication of the parent process.
  • Threads can exercise considerable control over threads of the same process whereas processes can only exercise control over child processes.
  • Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process while changes to the parent process do not affect child processes.


Q3. What are the advantages or usage of threads?

Ans:

  • Threads support concurrent operations. For example:
    Multiple requests by a client on a server can be handled as an individual client thread.
  • Threads often result in simpler programs.
    In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update.
  • Threads provide a high degree of control.
     Imagine launching a complex computation that occasionally takes longer than is satisfactory.
  • Threaded applications exploit parallelism.
     A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulate multi-tasking ("time sharing").

Q4. What are the two ways of creating thread?

Ans: There are two ways to create a new thread. Extend the 'Thread' class and override the 'run()' method in your class. Create an instance of the subclass and invoke the 'start()' method on it, which will create a new thread of execution.

public class NewThread extends Thread

{

public void run()

{

// the code that has to be executed in a separate new thread goes here

}

public static void main(String [] args)

{

NewThread c = new NewThread();

c.start();

}

}
This will implement the 'Runnable' interface. The class will have to implement the 'run()' method in the 'Runnable' interface. Create an instance of this class. Pass the reference of this instance to the 'Thread' constructor and a new thread of execution will be created.
public class NewThread implements Runnable

{

public void run()

{

// the code that has to be executed in a separate new thread goes here

}

public static void main(String [] args)

{

NewThread c = new NewThread();

Thread t = new Thread(c);

t.start();

}

}

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

Ans: 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.

Q6. Explain different way of using thread?

Ans: A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous when you are going for multiple inheritance.

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

Ans: 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 execute in same thread, so does not solve the purpose of creating a new thread.

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

Ans: 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.

Q9. What is ThreadLocal class? How can it be used?

Ans: 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 the case when multiple threads access a ThreadLocal instance, a separate copy of the Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be a singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)

ThreadLocal variable are difficult to understand and I recommend you to use best java book on concurrency: Java Concurrency in Practice

Q10. When InvalidMonitorStateException is thrown? Why?

Ans: 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.

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

Ans: 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 - let's say "lockObject"
  • Another thread T2 comes to execute the synchronized block and find that it's already acquired.
  • Now T2 calls lockObject.wait() method for waiting on the lock to be release by the T1 thread.
  • T1 thread finishes all its synchronized block work.
  • The T1 thread calls lockObject.notifyAll() to notify all waiting threads that it done using the lock.
  • Since the T2 thread is first in the queue of waiting it acquires the lock and starts processing.

Q12. Can two threads call two different synchronized instance methods of an Object?

Ans: No. If an 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 demonstrates it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods

public class Common {public synchronized void synchronizedMethod1() {System.out.println("synchronizedMethod1 called");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("synchronizedMethod1 done");} public synchronized void synchronizedMethod2() {System.out.println("synchronizedMethod2 called");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("synchronizedMethod2 done");}}public class MyThread extends Thread {private int id = 0;private Common common; public MyThread(String name, int no, Common object) {super(name);common = object;id = no;} public void run() {System.out.println("Running Thread" + this.getName());try {if (id == 0) {common.synchronizedMethod1();} else {common.synchronizedMethod2();}} catch (Exception e) {e.printStackTrace();}} public static void main(String[] args) {Common c = new Common();MyThread t1 = new MyThread("MyThread-1", 0, c);MyThread t2 = new MyThread("MyThread-2", 1, c);t1.start();t2.start();}}

Q13. How to implement Threads in java?

Ans: This is very basic threading question. Threads can be created in two ways i.e. by implementing java.lang.Runnable interface or extending java.lang.Thread class and then extending run method.

Thread has its own variables and methods, it lives and dies on the heap. But a thread of execution is an individual process that has its own call stack. Thread are lightweight process in java.

Thread creation by  implementingjava.lang.Runnableinterface.

We will create object of class which implements Runnable interface :

MyRunnable runnable=new MyRunnable(); Thread thread=new Thread(runnable);

Q14. When threads are not lightweight process in java?

Ans: Threads are lightweight process only if threads of same process are executing concurrently. But if threads of different processes are executing concurrently then threads are heavy weight process.

Q15. How can you ensure all threads that started from main must end in order in which they started and also main should end in last? (Important)

Ans: Interviewers tend to know interviewees knowledge about Thread methods. So this is time to prove your point by answering correctly. We can use join() methodto ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die. Calling join() method internally calls join(0);

Q16. What is race condition in multithreading and how can we solve it? (Important)

Ans: This is very important question, this forms the core of multi threading, you should be able to explain about race condition in detail. When more than one thread try to access same resource without synchronization causes race condition.

So we can solve race condition by using either synchronized block or synchronized method. When no two threads can access same resource at a time phenomenon is also called as mutual exclusion.

Q17. Why wait(), notify()  and notifyAll() are in Object class and not in Thread class? (Important)

Ans:

  • Every Object has a monitor, acquiring that monitors allow thread to hold lock on object. But Thread class does not have any monitors.
  • wait(), notify() and notifyAll()are called on objects only >When wait() method is called on object by thread it waits for another thread on that object to release object monitor by calling notify() or notifyAll()method on that object.

When notify() method is called on object by thread it notifies all the threads

which are waiting for that object monitor that object monitor is available now.

So, this shows that wait(), notify() and notifyAll() are called on objects only.

  • Wait(), notify() and notifyAll() method being in Object class allows all the threads created on that object to communicate with other.  .
  • As multiple threads exists on same object. Only one thread can hold object monitor at a time. As a result thread can notify other threads of same object that lock is available now. But, thread having these methods does not make any sense because multiple threads exists on object its not other way around (i.e. multiple objects exists on thread).
  • Now let’s discuss one hypothetical scenario, what will happen if Thread class contains wait(), notify() and notifyAll() methods?

Having wait(), notify() and notifyAll() methods means Thread class also must have their monitor.

Every thread having their monitor will create few problems -

>Thread communication problem.

>Synchronization on object won’t be possible- Because object has monitor, one object can have multiple threads and thread hold lock on object by holding object monitor. But if each thread will have monitor, we won’t have any way of achieving synchronization.

>Inconsistency in state of object (because synchronization won't be possible).

Q18. Is it important to acquire object lock before calling wait(), notify() and notifyAll()?

Ans: Yes, it’s mandatory to acquire object lock before calling these methods on object. As discussed above wait(), notify()  and notifyAll() methods are always called from Synchronized block only, and as soon as thread enters synchronized block it acquires object lock (by holding object monitor). If we call these methods without acquiring object lock i.e. from outside synchronize block then java.lang. IllegalMonitorStateException is thrown at runtime.

Wait() method needs to enclosed in try-catch block, because it throws compile time exception i.e. InterruptedException.

Q19. What is thread-safety? is Vector a thread-safe class?

Ans: Thread-safety is a property of an object or code which guarantees that if executed or used by multiple threads in any manner e.g. read vs write it will behave as expected. For example, a thread-safe counter object will not miss any count if same instance of that counter is shared among multiple threads. Apparently, you can also divide collection classes in two category, thread-safe and non-thread-safe. Vector is indeed a thread-safe class and it achieves thread-safety by synchronizing methods which modify state of Vector, on the other hand, its counterpart ArrayList is not thread-safe.

Q20. What happens when an Exception occurs in a thread? (answer)

Ans: This is one of the good tricky Java question I have seen in interviews. In simple words, If not caught thread will die, if an uncaught exception handler is registered then it will get a call back. Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. 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.

Q21. How do you share data between two thread in Java? (answer)

Ans: You can share data between threads by using shared object, or concurrent data structure like BlockingQueue. See this tutorial to learn  inter-thread communication in Java. It implements Producer consumer pattern using wait and notify methods, which involves sharing objects between two threads.