Tricky MultiThreading Interview Questions

TOP TRICKY DIFFICULT MULTITHREADING INTERVIEW QUESTIONS

What is multitasking ?

Executing several task simultaneously is called multitasking ?

What are the types of multitasking ?

  • Process Based Multitasking
  • Thread Based Multitasking

What is Process Based Multitasking ?

In Process Based Multitasking, multiple task are executed as a separate process for example writing on editor , listening music at same time etc. This time of multitasking is good at OS level.

What is Thread Based Multitasking ?

In Thread Based Multitasking ,multiple task are executed under same process.It is good for programmatic level.

What is the benefit of Multitasking ?

It reduces CPU idle time and increase performance.

What is the Thread ?

Thread is a light weight process in execution.

How can we create Thread ?

  • By Extending Thread Class
  • By Implementing Runnable Interface

What is Thread Scheduler ?

Thread scheduler schedules thread to execute.It is dependent of JVM so same Thread program can give different output at different JVM.Different Thread scheduler follows different algorithm like first come first serve, round robin etc.

Which method do we call to start Thread ?

start() method is called that starts new Thread.

Can we directly call run method of Thread instead of start ?

Yes we can but it will simple method call, it will not create separate Thread for execution.

Can we overload run() method ?

yes but start() will always call run method without parameter.

What are the states of Thread ?

  • New
  • Runnable
  • Running
  • waiting
  • Dead

Can we start Thread twice ?

No, we will get exception IllegalThreadStateException.

How can we return value from MultiThreading task ?

By implementing Callable interface instead of Runnable and override call method.Return value is received by Future Object.


package com.example.preparationforinterview;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class Myclass implements Callable<String> {
	String name;

	Myclass(String name) {
		this.name = name;
	}

	@Override
	public String call() throws Exception {
		return "Hello " + name;
	}

}

public class CallableExample {
	public static void main(String args[]) {
		Myclass myclass = new Myclass("I am learning Callbale Interface");
		ExecutorService exec = Executors.newCachedThreadPool();

		Future<String> response = exec.submit(myclass);
		try {
			System.out.println(response.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}

}

We get output as given below


Hello I am learning Callbale Interface

What is the significance of isDone method of Future ?

It shows that Future has completed its task , if we don't use this isDone method and directly call get method then get will block until execution completes.

What does it mean by priority of Thread ?

Priority informs to scheduler about importance of Thread.Ideally Scheduler should run highest priority Thread first but order, in which a set of Thread will execute is indeterminate.It has range from 1 to 10 with 1 minimum and 10 maximum.

What is default priority ?

Default priority of main Thread is 5 and other Thread inherits default priority from parent Thread.

What is the significance of yield method ?

yield method informs to scheduler to give chance to execute other Thread of same priority.If no Thread is already waiting then it continues to run.

What is the use of join method ?

When a Thread wants to wait until other Thread completes its job then join method is used for example if Thread t1 wants to wait until Thread t2 completes its job then from t1 execution t2.join() is called.

What is Daemon Thread ?

Daemon Thread is a Thread that runs in background as long as program is running.So when all non daemon Thread terminates then program also terminates and daemon Threads are also killed for example garbage collector,listener etc.

How can i make a Thread as Daemon Thread ?

Calling setDaemon(true) on Thread.It should be called before start method. Any Thread created by Daemon Thread will also be a Daemon Thread.

Can a Thread be made Daemon after running it ?

No , after running if we do setDaemon(true) then we will get IllegalThreadStateException.

When a Thread can interrupt other Thread ?

If Thread wants to interrupt to target Thread then target Thread should be in sleeping/waiting state.if target Thread is not in sleeping/waiting state then then Thread can not interrupt target Thread.When a Thread is interrupted its isInterrupted flag will be set however this flag is cleared when the exception is caught that's why in catch this flag is false always in catch block.

How can we handle exception in Thread ?

When we throw any exception from run then by default it will always go to console, so using Thread.UncaughtExceptionHandle we can handle exception.It can be understood with an example.


package com.example.preparationforinterview;

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
	public void uncaughtException(Thread t, Throwable e) {
		System.out.println("Exception handles " + e);
	}
}

class MyExceptionThread implements Runnable {
	public void run() {
		Thread t = Thread.currentThread();
		System.out.println("current Thread " + t);
		throw new RuntimeException();
	}
}

public class ExceptionHandlingExample {
	public static void main(String[] args) {
		Thread a = new Thread(new MyExceptionThread());
		a.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
		a.start();
	}
}

Output will be as follows


current Thread Thread[Thread-0,5,main]
Exception handles java.lang.RuntimeException

Where can we use synchronized modifier ?

Method level and block level

What is the advantage of synchronized keyword ?

It prevents data inconsistency problem.

What is the disadvantage of synchronized keyword ?

It slows the performance

A Thread which has lock on class level then can other Thread access synchronized method (without static)

Yes

What is the advantage of synchronized keyword over explicit Lock objects ?

In synchronized keyword we require to write less code, so user error is greatly reduced.

What is the advantage of explicit Lock objects over synchronized keyword?

If there is any exception we can easily do clean up action.In explicit lock we can try and and fail to acquire a lock, or try to acquire a lock for a certain amount of time and then give up.

What is the significance of volatile keyword ?

When a task does any changes on variable its possible that changes is not visible to other task because in multi processors, task saves changes on local cache. If we declare a variable as volatile then task directly writes or reads variable value from main memory.Synchronization also flushes changes to main memory.

When should i use synchronized block ?

If instead of synchronize complete method we want to synchronize only small part of method then synchronized block is used.its performance is better than synchronized method.

What is Thread local storage ?

Thread local storage creates different storage for same variable of an Object shared among multiple Threads.

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

  • sleep method does not releases the lock of an object while wait does so that other task can obtain lock and can complete its work.
  • sleep and wait both have overloaded method in which they can specify time for waiting but using notify or notifyAll wait can be waken again before time ends.
  • wait is part of Object class while sleep is part of Thread class.

What will happen if we call wait(), notify() and notifyAll() within a method which is not synchronized ?

IllegalMonitorStateException will be thrown.

What are the methods used for Thread communication ?

  • wait
  • notify
  • notifyAll

Does notifyAll() awake all task which are in waiting state ?

No, only those tasks are awaken which are waiting for particular lock.

What is the substitute of wait(), notify(),notifyAll() when using explicit locking ?

await(), signal(), signalAll().

Does wait() releases lock immediately ?

Yes

Does notify() and notifyAll() releases lock immediately ?

No

What is Deadlock ?

If one Thread has lock on one Object and waits for other Object to get lock which is locked by other Thread already and that other Thread is also waiting for lock of Object which is already locked by first Thread then this condition is called deadlock.

What is starvation ?

If a Thread waits for any resource for long time but waiting ends at certain point is called starvation.For example low priority Thread waits to complete all high priority Thread, it might be long waiting but waiting will ends at certain point.

What are the two model followed by java multithreading system ?

  • Green Thread Model
  • Native OS Model.

What is Green Thread ?

Threads which are managed by only JVM not by OS is called Green Thread.It is deprecated.

What is Native OS Model ?

JVM manage Thread by support of OS.

What is CountDownLatch ?

It is part of java.util.concurrent library.Using this we can synchronize one or more tasks by forcing them to wait for the completion of a set of operations being performed by other tasks.We give one initial count to CountDownLatch and if any Thread calls await() the it waits there until count reaches zero.

What is CyclicBarrier ?

It create a group of tasks to perform work in parallel.All parallel task are brought into alignment at one place so that all can move together.

What is the difference between CountDownLatch and CyclicBarrier

  • CountDownLatch is one shot event, it can not be used again and again.
  • In CyclicBarrier we can attach action as well that is executed automatically when the counter reaches zero.

What is DelayQueue ?

It implements the Delayed interface.It is unbounded BlockingQueue of objects. An Object is taken out from queue if it has expired.If no delay has expired then no Object will be in Queue.

What is PriorityBlockingQueue ?

In this, Object have some priority number and that emerges as priority number.

What is the use of Semaphore ?

Using Semaphore, multiple task can access same resources while in synchronized only a single is allowed to access a resource.

What is the significance of tryLock() ?

This method tries to get lock if it gets lock then it perform some secured operation but if it does not get lock then it does not wait while does alternative operation.

What is InheritableThreadLocal ?

This class extends ThreadLocal class.By default ThreadLocal values is not available when child Thread is created by parent Thread but InheritableThreadLocal provides inheritance of values from parent thread to child thread.By overriding childValue() we can give our own customized value to child Thread.Before chile Thread is started overridden childValue() is called.

package com.example.preparationforinterview;

class Parent extends Thread {
	public static InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal() {
		public Object childValue(Object parentValue)
		{
			return "child value";
		}
	};
	public void run()
	{
		inheritableThreadLocal.set("parent value");
		System.out.println("Parent Thread :" + inheritableThreadLocal.get());

		ChildThread child = new ChildThread();
		child.start();
	}
}
class ChildThread extends Thread {

	public void run()
	{
		System.out.println("Child Thread :" + Parent.inheritableThreadLocal.get());
	}
}
public class InheritableThreadLocalExample {

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

Output is


Parent Thread :parent value
Child Thread :child value

Give one example using Thread in which Thread executes three methods in sequence like m1() should be executed first then m2() and after that m3(). m1(),m2(),m3() is methods written in shared resource ?


package com.example.preparationforinterview;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

class MyMethods{
	
	Semaphore s1 = new Semaphore(1);
	Semaphore s2 = new Semaphore(0);
	Semaphore s3 = new Semaphore(0);
	
	public void m1(){
		System.out.println("m1");
		s2.release();
	}
	public void m2(){
		System.out.println("m2");
		s3.release();
	}
	public void m3(){
		System.out.println("m3");
		s1.release();
	}
}

class M1Thread implements Runnable{
	private MyMethods myMethods;
	
	M1Thread(MyMethods myMethods){
		this.myMethods = myMethods;
	}

	@Override
	public void run() {
		try {
			while(true){
			myMethods.s1.acquire();
			myMethods.m1();
			Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
}

class M2Thread implements Runnable{
	private MyMethods myMethods;
	
	M2Thread(MyMethods myMethods){
		this.myMethods = myMethods;
	}

	@Override
	public void run() {
		try {
			while(true){
			myMethods.s2.acquire();
			myMethods.m2();
			Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
}

class M3Thread implements Runnable{
	private MyMethods myMethods;
	
	M3Thread(MyMethods myMethods){
		this.myMethods = myMethods;
	}

	@Override
	public void run() {
		try {
			while(true){
			myMethods.s3.acquire();
			myMethods.m3();
			Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
}

public class MethodCalls {
	
	public static void main (String args[]){
		ExecutorService executorService = Executors.newCachedThreadPool();
		MyMethods myMethods = new MyMethods();
		executorService.execute(new M1Thread(myMethods));
		executorService.execute(new M2Thread(myMethods));
		executorService.execute(new M3Thread(myMethods));
		executorService.shutdown();
	}

}

What is Thread Pool ?

ThreadPool is collection of Threads.In ThreadPool we specify number of Thread if any Thread is available then then its picks task from queue and executes it but if Thread is not available then task waits for Thread to be idle.Advantage of ThreadPool is it eliminates the delay introduced by thread creation, application is more responsive, solution of resource thrashing.

Why destroy() and suspend() methods are deprecated ?

If any Thread has lock on any Object and if we suspend or destroy that Thread then lock on object is not released and can create deadlock.

Write custom Semaphore (acquire () and release()).


package com.example.preparationforinterview;

public class MyCustomSemaphore {
	private int permits;

	public MyCustomSemaphore(int permits) {
		this.permits = permits;
	}

	public synchronized void release() {
		permits++;

		if (permits > 0)
			this.notifyAll();
	}

	public synchronized void acquire() throws InterruptedException {
		if (permits > 0) {
			permits--;
		} else {
			this.wait();
			permits--;
		}
	}

}

Write our custom CountDownLatch .

package com.example.preparationforinterview;

public class MyCustomCountDownLatch {
	private int count;

	public MyCustomCountDownLatch(int count) {
		this.count = count;
	}

	public synchronized void await() throws InterruptedException {
		if (count > 0)
			this.wait();
	}

	public synchronized void countDown() {
		count--;

		if (count == 0)
			this.notifyAll();
	}

}

Write our custom BlockingQueue .

package com.example.preparationforinterview;

import java.util.LinkedList;
import java.util.List;

interface BlockingQueueCustom {

	void put(E item) throws InterruptedException;

	E take() throws InterruptedException;
}

class MyCustomBlockingQueue<E> implements BlockingQueueCustom {

	private List<E> myQueue;
	private int maxQueueSize;

	public MyCustomBlockingQueue(int maxQueueSize) {
		this.maxQueueSize = maxQueueSize;
		myQueue = new LinkedList();
	}

	public synchronized void put(E item) throws InterruptedException {

		if (myQueue.size() == maxQueueSize) {
			this.wait();
		}

		myQueue.add(item);
		this.notify();
	}

	public synchronized E take() throws InterruptedException {

		if (myQueue.size() == 0) {
			this.wait();
		}

		this.notify();
		return myQueue.remove(0);
	}
}




Visit Others Links

Interview Questions Top Elasticsearch Interview Question
Top Kubernetes Interview Question
Top HTTP Interview Question
Top PouchDB Interview Question
Top Pivotal Cloud Foundry (pcf) Interview Question
Top Apache Camel Interview Question
Top Docker Interview Question
Top Gradle Interview Question
Top Generics Interview Questions In Java
Java 9 Interview Questions
Top Maven Interview Question
Top RabbitMQ Interview Question
Top Spring Batch Interview Question
Top Spring Boot Interview Question
Top Tika Interview Question
Top Kotlin Interview Question
Top OpenShift Interview Question
Top Polymer Interview Question
Top WebGL Interview Question
Top Continuous Integration Interview Question
Top Spring Cloud Interview Question
Top JOGL Interview Question
Top JFreeChart Interview Question
Java MultiThreading Interview Question
Top Spring ROO Interview Question
Top Seaborn Interview Question
Top TestRail Interview Question
Top LolCode Interview Question
Top Spring Transaction Management Interview Question
Top DynamoDB Interview Question
Top PySpark Interview Question
Top SaltStack Interview Question
Top Spring AOP Interview Question
© 2019 PreparationForInterview.com