Sunday, September 17, 2023

Top 15 Java Multithreading, Concurrency Interview Questions Answers asked in Investment banks

Multi-threading and concurrency questions are an essential part of any Java interview. If you are going for any Java interview on any Investment bank like Barclays, Citibank, Morgan Stanley, etc for the Cash Equities Front Office Java Developer position, you can expect a lot of multi-threading interview questions on your way. Multi-threading and concurrency are favorite topics on Investment banking interviews,  especially on electronic trading development jobs and they grill candidate on many tricky java thread interview questions. They just want to ensure that the guy has a solid knowledge of multi-threading and concurrent programming in Java because most of them are in the business of performance which provides them a competitive advantage and it's hard to write correct and robust concurrent code.

For example, high volume and low latency Electronic Trading Systems which are used for Direct to Market (DMA) trading are usually concurrent in nature.  Most of the time the focus on microsecond latency, that's why a good knowledge of how to use effectively to minimize latency and improve throughput is important.

These are some of my favorite thread interview questions on Java asked on different on a different time. I am not providing an answer to these thread interview questions but I will give you hint whenever possible, some time hint is also enough to answer. I will update the post further with detailed answers just like I did for 10 Singleton interview questions in Java recently.

After the introduction of the concurrency package in JDK 1.5 questions on concurrent utility and concurrent collections were increased like ThreadLocal, BlockingQueue, Counting Semaphore, and ConcurrentHashMap become popular.

The same is true for Java 8 and Java 9, where questions on lambda expression and parallel streams, new fork-join pool, CompletableFuture is also on the rise in 2018 and will remain in 2019. Hence you should prepare well for those topics.

And, if you are preparing for Java interviews then you can also checkout my book Grokking the Java Interview Volume 1 and 2 which covers most of the Java topics including multithreading, concurrency, serialization, classloader, performance and debugging and many more. You can also use code friends20 to get 20% discount now for a limited time. 






15 Java Thread Interview Questions with Answers

Anyway, without any further ado, here is my list of some of the frequently asked Java multithreading and concurrency questions from Java developer Interviews on Investment banks e.g. Barclays, Morgan Stanley, Citibank, etc.


1. You have thread T1, T2, and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
This thread interview question is mostly asked in the first round or phone screening round of interviews and the purpose of this multi-threading question is to check whether the candidate is familiar with the concept of the "join" method or not. 

The answer to this multithreading question is simple it can be achieved by using the join method of Thread class. If you are not familiar with the join method, please see my post on how to join threads in Java.



2. What is the advantage of a new Lock interface over a synchronized block in Java? You need to implement a high-performance cache which allows multiple readers but the single writer to keep the integrity how will you implement it?
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate locks for reading and writing which enables you to write high-performance data structures like ConcurrentHashMap and conditional blocking.

This java thread interview question is getting increasingly popular and more and more follow-up questions come based on the answer of the interviewee.

I would strongly suggest reading about Locks before appearing for any Java multi-threading interview because nowadays It's heavily used to build cache for an electronic trading system on client and exchange connectivity space.

And, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at the Java Multithreading, Concurrency, and Performance Optimization course by Michael Pogrebinsky on Udemy. It's an advanced course to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance

How forkjoin pool works in Java




3. What are the differences between the wait and sleep method in Java?
Another frequently asked thread interview question in Java mostly appear in a phone interview. The only major difference is that wait releases the lock or monitor while sleep doesn't release any lock or monitor while waiting. 

The wait is used for inter-thread communication while sleep is used to introduce pause on execution. See my post wait vs sleep in Java for more differences



4. Write code to implement a blocking queue in Java?
This is a relatively tough Java multi-threading interview question that serves many purposes, it checks whether a candidate can actually write Java code using thread or not, it sees how good the candidate is at understanding concurrent scenarios and you can ask a lot of follow-up question based upon his code. If he uses the wait() and notify() method to implement blocking queue, 

Once the candidate successfully writes it you can ask him to write it again using new Java 5 concurrent classes etc.



5. Write code to solve the Produce consumer problem in Java? (solution)
Similar to the above questions on the thread but more classic in nature, some time interviewer ask to follow up questions  How do you solve the producer-consumer problem in Java, well it can be solved in multiple ways, I have shared one way to solve the producer-consumer problem using BlockingQueue in Java, so be prepared for surprises. Sometimes they even ask to implement a solution to the dining philosopher problem as well.


6. Write a program that will result in a deadlock? How will you fix deadlock in Java?
This is my favorite java thread interview question because even though deadlock is quite common while writing a multi-threaded concurrent program many candidates not able to write deadlock-free code and they simply struggle.

Just ask them you have N resources and N threads and to complete an operation you require all resources.

Here N can be replaced with 2 for the simplest case and a higher number to make the question more intimidating. You can further check the Applying Concurrency and Multi-threading to Common Java Patterns course on Pluralsight to learn more about popular concurrency patterns and the right way to use them.

Top 15 Java Multithreading, Concurrency Interview Questions Answers asked in Investment banks



7, What is an atomic operation? What are atomic operations in Java?
Simple java thread interview questions, another follow-up is do you need to synchronize an atomic operation? :) You can read more about java synchronization here.



8. What is a volatile keyword in Java? How to use it? How is it different from the synchronized method in Java?
Thread questions based on a volatile keyword in Java has become more popular after changes made on it on Java 5 and Java memory model. It’s good to prepare well about how volatile variables ensures visibility, ordering, and consistency in a concurrent environment.



9. What is a race condition? How will you find and solve the race conditions?
Another multi-threading question in Java which appear mostly on senior-level interviews. Most interviewer grill on recent race condition you have faced and how did you solve it and sometimes they will write sample code and ask you to detect race condition. See my post on the Race condition in Java for more information.

In my opinion, this is one of the best java thread interview questions and can really test the candidate's experience in solving race condition or writing code which is free of data race or any other race condition.

One of the best books to get the mastery of this topic is "Java Concurrency in Practice by Brian Goetz". If you are thinking that this book is old then think again, it's still relevant in the era of Java 11.




10. How will you take a thread dump in Java? How will you analyze the Thread dump?
In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he asks how you analyze it. A thread dump can be useful to analyze deadlock situations as well.



11. Why we call the start() method which in turn calls the run() method, why not we directly call the run() method?
Another classic java multi-threading interview question This was my original doubt when I started programming in the thread. Now days mostly asked in a phone interview or first round of interview at mid and junior-level java interviews.

The answer to this question is that when you call the start() method it creates a new Thread and executes code declared in the run() while directly calling the run() method doesn’t create any new thread and execute code on the same calling thread. Read my post Difference between start and run method in Thread for more details.

difference between start and run method in Java




12. How will you awake a blocked thread in Java?
This is a tricky question on threading, blocking can result in many ways, if the thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand, if the thread is blocked due to result of calling wait(), sleep(), or join() method you can interrupt the thread and it will awake by throwing InterruptedException. See my post How to deal with blocking methods in Java for more information on handling blocked thread.



13. What is the difference between CyclicBarriar and CountdownLatch in Java? (answer)
New Java thread interview questions mostly to check familiarity with JDK 5 concurrent packages. One difference is that you can reuse CyclicBarrier once the barrier is broken but you can not reuse CountDownLatch. If you want to learn more see Multithreading and Parallel Computing in Java course on Udemy.




14. What is an immutable object? How does it help in writing a concurrent application?
Another classic interview questions on multi-threading, not directly related to the thread but indirectly helps a lot. This java interview question can become more tricky if ask you to write an immutable class or ask you Why String is immutable in Java as a follow-up.



15. What are some common problems you have faced in multi-threading environment? How did you resolve it?
Memory-interference, race conditions, deadlock, livelock, and starvation are an example of some problems comes in multi-threading and concurrent programming. There is no end to a problem if you get it wrong and they will be hard to detect and debug.

This is mostly an experienced-based interview question on a java thread instead of fact-based. You can further see Java Concurrency in Practice Course by Heinz Kabutz for some real-world problems faced in actual high-performance multi-threaded applications.

Java Concurrency in Practice Course by Heinz Kabutz


These were some of my favorite Java thread interview questions and mostly asked on Investment banks. This list is by no means complete so please contribute some of the interesting java thread questions you have faced during the interview.  

The purpose of this article is to collect and share great interview questions on the multi-threading concept which not only helps in the interview but opens the door for learning a new threading concept.


Update:

One of the Javarevisited readers, Hemant has contributed some more thread interview questions in Java, though he hasn’t provided answer sand left that job for me, I will certainly do when time allows, just like I have recently updated 10 Singleton interview question in Java with answers.

If you guys know answers to this Java concurrency questions then please post a comment.

Here are his comment “Good questions on multi-threading though you may need to prepare more in order to clear any multi-threading interview, you need to be familiar with the concept of immutability, thread-safety, race condition and many more.

10 or 15 questions is good for the quick recap but you at least need to prepare more than 50 questions on threading and concurrency to perform better on Java interview.

 You can find some interesting thread question below which is no doubt highly popular –

1) Difference between green thread and native thread in Java?

2) Difference between thread and process? (answer)

3) What is context switching in multi-threading?

4) Difference between deadlock and livelock, deadlock, and starvation?

5) What thread-scheduling algorithm is used in Java?

6) What is a thread-scheduler in Java?

7) How do you handle an unhandled exception in the thread?

8) What is thread-group, why it's advised not to use thread-group in Java?

9) Why the Executor framework is better than creating and managing thread by the application?

10) Difference between Executor and Executors in Java? (answer)

11) How to find which thread is taking maximum CPU in windows and Linux servers?

12) Difference between virtual thread and normal thread in Java?

Apart from practicing these question answers, more important is to understand the concept behind these multi-threading questions simply mugging the answers of these thread interview questions is not going to help because there would be a lot of follow-ups based on your answer and if you haven't mastered the particular thread topic it would be difficult to answer them.



Other Java Interview Questions on different topics you may like to Explore
Thanks for reading this article so far. If you like these multi-threading and Concurrency Interview questions then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P.S. - If you can't solve these questions and looking for online courses to learn Java Multithreading and Concurrency then you can also check out my list of best Concurrency Courses for Java programmers to explore this important topic in depth. 

And now, over to you, what was the last question you were asked on Thread or concurrency in Java? 

35 comments :

Anonymous said...

Indeed a great collection of java multi-threading interview questions and I agree with you. wall street firms really need people who are very strong in multi-threading and concurrent programming. you could probably include more interview questions from new Thread classes added on JDK5

Anonymous said...

answers of your thread interview questions are not proper. you should work to make your interview questions and answers more relevant, accurate and better. Though I agree that multi-threading is not an easy thing to achieve and multi-threading interview is real tough.

Anonymous said...

Thanks for another great post! You're very smart, and you're writing really important articles. That being said, you have to get an editor! Your spelling, grammar, and punctuation distract from otherwise amazing content. Writing is a great way to get better at writing, but you can get better even faster with feedback from writers with more skill than yourself. In any case, you rock and have amazing potential.

Javin@ OutOfMemoryError in Java said...

@Anonymous, thanks for your feedback , English not being my first language, it has some characteristic or effect of Hindi in grammar and work flow.I love to make my English flawless and increase reading experience of my readers but more importantly I like to share my experience and until I connect to my readers or my fellow developers I am happy and it motivates me to improve. Once again thanks for your feedback appreciate.

Javin

Javin @ OutOfMemoryError in Perm Gen Space said...

Hi Vineet, its indeed a interview question guide, you can easily find detailed answer for these multi-threading question by doing google, Though I have also provided pointers and main point which some one will look. would be great if you could contribute some good answer and I will include in post.

Anonymous said...

Usage of Singleton Pattern in Java API

java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()

Garima said...

I am looking for some more thread questions and answers in Java, your thread questions are good but I need more tough thread interview questions something which is new and not everybody know about those interview questions.Please help

Anonymous said...

Question: what are the benfits we will get when we extend a java.lang.Thread class instead of implimenting Runnable interface?

Unknown said...

Good list of questions. I have listed frequently asked multi-threading interview questions and answers at http://java-success.blogspot.com.au/2011/09/java-multi-threading-interview.html that will be very handy as well.

Javin @ spring interview question answer said...

Thanks Arul. you like these thread interview questions. glad to here that.

Javin @ Servelt Interview Questions said...

Thanks Kamal. I have shared many of those in my blog, just use search box on top left. by the way here are few :
10 questions on Singleton Pattern in Java
Why String is immutable in Java

Peter Lawrey said...

1. I would call run() instead of start() ;)

2. I would make it clear there is a difference between ReentrantLock and ReentrantReadWriteLock.

4. While I started programming Java before version 5.0, many people started programming after 2004, so I wouldn't consider the concurrency library that new as there when many people started. BTW It was available as a separate library from 1998

6. My favourite answer to this is to create a Thread in a static block which access the class and does a join. This creates a deadlock with just one new thread and no explicit locking. ;)

8. Another question I get is the difference in volatile between Java and C++

10. You might add, how do you take a thread dump programmatically.

Excellent posts, keep them up.

Javin @ thread safe class in java said...

Hi Peter, Good to see you back here :) difference between volatile in Java and C++ is a good question if you mention C++ in your resume and also taking a thread dump programmatically and with command prompt in case of deadlock is a good skill to have. What is current trend, have you spotted any new trend related to concurrency in Java interviews ?

Anonymous said...

Can you please share some multi-threading questions asked in Google Interviews. I am very interested on what these top companies like Google, Amazon, Facebook or Investment banks like Nomura or Goldman asked in Java, JVM and Threading. Thanks

johnny1980 said...

Is it possible that interviewers do not always know the answers, and are taking advantage of job interviews to get free software consultancy?

Javin @ transient vs volatile said...

@Jon, You bring the very interesting point about Java interviews,Many do and which I guess is not bad because if some one can solve the problem you are facing than it's good signal that guy can be useful.

Anonymous said...

Please try to answer question dont leave reader in dark room

Anonymous said...

Javin, really good questions. Just another query which core java book you recommned to understand concepts.

Skye Night said...

@Javin : The main advantage of new Locks over Synchronized block is to handle Deadlock better way. In blocks once deadlock happens you have no way to fix it unless restart the jvm but Lock gives you tools to handle deadlock situations. Other benefits are bonus :)

Rashi said...

Hi Guys, I would like to share one of the Interview Question related to ThreadPool implementation. I was asked in JP Morgan and Chase that , What should you take care, if you have to make your own Thread Pool? I thought about Executors framework of Java 5 but couldn't answer much. I am interested in points, what are the important points one should take care while creating there own thread pool in Java?

Thx
Rashi

Anonymous said...

I was asked to implement thread pool in java as well and they were interested in knowing key things you would consider to design pool

Andrew said...

Why knowledge of multithreading in Java is so important to get a Job? What makes it so desirable and same time tough to get master?

Unknown said...

Javin, I am a Java developer with 10+ years of experience and accidentally bumped into your blog around 15 days ago. Since then, I am stuck with it :-). I tried to read thru so many articles that you wrote and they are extremely useful and extremely well written with a lot of clarity on the fundamental concepts! Its a great job! Keep it up!

I have a couple of questions on threads:
1. Is "a thread of execution" same as "thread object" ?
2. Lets say, there is a java application (in real production scenario) and it can accept concurrent requests.. implies, multiple users can get data from this application while it is running in production.. and I can see the logs that multiple "threads" are running in the log.. like say, Thread-1, Thread-2, Thread-23, Thread-50.. etc.. based on the number of "concurrent" requests it is processing.
My question is, is this concurrency same as "multi threading within an application"? Or is it different? Can a java application handle concurrent requests (from multiple users/sessions) simultaneously by default? How does it work? Please let us know.

Best wishes..

Sekhar babu Karri said...

package com.learning.material;

public class MyThread {

/**
* @param args
*/
public static void main(String[] args) throws InterruptedException {

System.out.println("i am the Main thread...starting......");

final Thread t1 = new Thread(){
public void run(){
System.out.println("i am thread 1 starting......");
try{
Thread.sleep(5000);
System.out.println("I am Thread 1 finished ");
}catch(InterruptedException ie){
System.out.println("Exception:"+ie.getMessage());
}
}
};

final Thread t2 = new Thread(){
public void run(){
try{
t1.join();
System.out.println("I am Thread 2 finished ");
}catch(InterruptedException ie){
System.out.println("Exception:"+ie.getMessage());
}
}
};

Thread t3 = new Thread(){
public void run(){
try{
t2.join();
System.out.println("I am Thread 3 finished ");
}catch(InterruptedException ie){
System.out.println("Exception:"+ie.getMessage());
}
}
};
t1.start();
t2.start();
t3.start();
t3.join();

System.out.println("i am Main thread finished");

}

}

Gopal said...

I think you could do better by adding few more multithreading and concurrency questions from java.util.concurrent package e.g.

1) Difference between Callable and Runnable interface in Java?
2) What is FutureTask in Java? What is benefit of using it?
3) Difference between Thread.isInterrupted() and Thread.interrupt() method?
4) How ConcurrentHashMap achieves scalability?
5) What is Semaphore in Java?
6) Difference between ReentrantLock and synchronized keyword in Java?
7) What is ReadWriteLock in Java?
8) What is busy spinning?
9) Difference between notify() and notifyAll() in Java? When do you use notifyAll() over notify()?
10) Difference between wait, sleep and yield in Java?
11) Difference between Runnable vs Thread in Java?
12) Why wait and notify methods are called from synchronized block or method in Java?
13) What is doubled checked locking of Singleton?
14) Difference between LiveLock and Starvation in Java?
15) What is daemon thread in Java? What is use of daemon threads?
16) Why wait, notify and notifyAll are in Object class instead of Thread?
17) Why wait method is called from loop in Java
18) Difference between wait method and Condition object in Java?
19) Write code for getInstance() method of thread-safe Singleton in Java?
20) What is Java Memory Model?
21) Can we make static method synchronized in Java?
22) What is lock stripping?
23) How many thread is created by Timer class?
24) What is ThreadLocal in Java?
25) What is ThreadLocal memory leak in Java? How to fix that?
26) What is race condition in Java? Have you ever faced race conditions?
27) What is thread-safety? What are few ways to achieve thread-safety in multithreading code?
28) Difference between synchronized method and block in Java? Which one is better?
29) Difference between volatile and transient variable in Java?
30) How to check if a Thread holds a Lock in Java?

cbp said...

Thanks for the list of questions and all the great comments. I wanted to point out an error in #11 though.

When you call the start() method in the Thread class, it does not directly call the run() method. It calls a native code method start0(). This native code will only schedule the thread to be executed with the ThreadScheduler. The JVM will then grab the item from the ThreadScheduler and execute the run() function. It is very similar to a Strategy Pattern from GoF where the JVM knows how to execute a strategy and a Thread class defines what the strategy is that is to be executed.

Unknown said...

Hi Guys,
This is Nihar.I have one question from threading concept i.e in an application 0-10 thread is good or 10-100 thread..which one & why????

Anonymous said...

This was asked in my recent interview .
Object ob1 has two methods A and B.
You have two Threads (Thread 1 and Thread 2)

Question is I should be access Method A of Ob1 from Thread 1 and at the same time Thread 2 should be able to access Method B of Ob1.

However if Thread 1 is using Method A , then Thread 2 should not be able to use Method A of Ob1.
How is this possible ?? One hint given was Monitors :-)

Anonymous said...

answer of question 1:

MyRunnable.java
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(){

}
public MyRunnable(String name){
this.name=name;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
System.out.println("Thread name - "+Thread.currentThread().getName()+" i = "+i);
}
}

}

Main.java
public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable runnable=new MyRunnable();
Thread t1=new Thread(runnable,"Thread1");
Thread t2=new Thread(runnable,"Thread2");
Thread t3=new Thread(runnable,"Thread3");
try{
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
}catch(InterruptedException ie){
ie.printStackTrace();
}
}

}

Anonymous said...

While execution , a thread in ExecutorFramework throws some exception.How can we notify this exception to the calling application.

Anonymous said...

good questions. But your answers are not to the point. You are saying "this topic is also important. This.. That.. etc". But you are not explaining the actual answer properly. It will be better if you can focus on the answer.

For the 1st question, your answer was this...
"This thread interview question is mostly asked in the first round or phone screening round of interview and purpose of this multi-threading question is to check whether the candidate is familiar with the concept of "join" method or not."

But you didn't explain how it can be achieved using "join"
is it something like this in main method..?
T1.start();
T1.join();
T2.start();
T2.join();
T3.start();
T3.join();

janu said...

I tried answering the above questions, for few i attached the source link, please feel free to go through and let me know if anything wrong.

1) Difference between green thread and native thread in Java?
A)
• Green threads are scheduled by a virtual machine.
• Native threads are scheduled by a operational system.

2) Difference between thread and process? (answer)
A) Threads are lightweight, an independent path of execution in the process. They share same address space of the process and less overhead compared to process. Process are an individual program, require their own address space and has more overhead than threads. Also, the difference between Thread and process depends upon operating system implementation. For example, there is very less difference between a thread and a process in Linux than Windows.
3) What is context switching in multi-threading?
A) a context switch is the process of storing the state of a process or of a thread, so that it can be restored and execution resumed from the same point later. This allows multiple processes to share a single CPU, and is an essential feature of a multitasking operating system

4) Difference between deadlock and livelock, deadlock and starvation?
A) A deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock. A livelock on the other hand is almost similar to a deadlock, except that the states of the processes involved in a livelock constantly keep on changing with regard to one another, none progressing. Thus Livelock is a special case of resource starvation, as stated from the general definition, the process is not progressing.

5) What thread-scheduling algorithm is used in Java?
A) Execution of multiple threads on a single CPU in some order is called scheduling. The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-priority scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable threads.

6) What is thread-scheduler in Java?
A) Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

7) How do you handle an unhandled exception in the thread?
A) When a task throws an exception that it does not handle, the runtime prints theexception stack trace to the console and then returns the thread to the threadpool. There is no such thing as an unhandled exception on a thread created with the Start method of the Thread class.

8) What is thread-group, why its advised not to use thread-group in Java?
A) https://stackoverflow.com/questions/3265640/why-threadgroup-is-being-criticised
9) Why Executor framework is better than creating and managing thread by the application?
A) Because of that creating a ThreadPool is much better solution. Using ThreadPool we can limit the number of threads can be pooled and reused. Executors framework facilitate process of creating Thread pools in java. Executors class provide simple implementation of ExecutorService using ThreadPoolExecuto

10) Difference between Executor and Executors in Java? (answer)
A) https://javarevisited.blogspot.com/2017/02/difference-between-executor-executorservice-and-executors-in-java.html

11) How to find which thread is taking maximum CPU in windows and Linux server?
A) https://backstage.forgerock.com/knowledge/kb/article/a39551500



Rakib said...

Javin, really good questions. Just another query which core java book you recommned to understand concepts.



Read more: https://javarevisited.blogspot.com/2018/07/java-multi-threading-interview-questions-answers-from-investment-banks.html#ixzz6omfHG82P

javin paul said...

Hello Rakib,

I recommend Core Java by Cay S. Horstmann and Effective Java by Joshua Block, if you need a complete list you can check my list of best core java books for beginner

Anonymous said...

One of the benefits is when your class is already extending another class. You must implements the Runnable interface since in Java you can extends only ONE class

Post a Comment