Sunday, September 10, 2023

Top 12 Java Thread, Concurrency, and Multithreading Interview Questions Answers

Hello guys, Multithreading is an important feature of the Java programming language, which means threads are also an important part of any Java interview. It's true and in fact, at beginners and freshers, level Thread interview questions in Java are one of the most difficult to answer. One reason for interview questions related to multithreading and concurrency being difficult is confusion around how multiple threads work together and the second is threads are genuinely a complicated topic to understand and use correctly.

Mostly thread interview questions check Java programmer's knowledge on Java Thread API, Java concurrency API, issues related to multi-threading like a race condition, thread-safety, and deadlock.

Some time multithreading and concurrency interview question also focus on parallel design patterns like solving the producer-consumer problem, implementing work steal pattern, or solving dining philosopher problem in Java. This is especially true while interviewing experienced Java developers with 4 to 6 years of experience.

In this article, we will take a look at different kinds of multithreading and concurrency questions asked in various interviews like on telephonic or face-to-face interviews, on written tests, to both experienced and senior Java developers, and some tips to answer them correctly.

Questions asked on telephonic or the first round of interviews are tend to be easier and you must answer them to the point with a keyword, which the interviewer is expecting. On the face-to-face interview, be prepared for different kinds of follow-up questions.

Btw, if you are a complete beginner to Java threads, I strongly suggest you join a hands-on multithreading course like Multithreading and Parallel Computing in Java from Udemy. It's a great course to learn thread basics It's also very affordable and you can get in just $9.9 on Udemy sales.




12 Java Thread Concurrency Interview Questions and Answers

As I said, in this Java article, not only,  I will share some of the most commonly asked thread interview questions at the freshers and beginners level, like up to 2 to 4 years of experience, and some tips and tricks to answer them correctly.

By the way, these thread interview questions are equally useful for senior Java developers or guys with some Java experience in hand. I have tried to share answers to these interview questions on the thread as well but I suggest you do some research and learn the topic well to answer any follow-up questions, which comes due to your response to these thread questions in Java.

If you need some resources to prepare for multithreading interviews then you can also check out Java Multithreading for Senior Engineering Interviews course from Educative. A text-based interactive coding platform and the best place to prepare for coding interviews. This course contains solutions to a lot of classic concurrency problems like producer-consumer, readers-writers, dining philosophers, etc.


Anyway here is my collection of Java thread interview questions and how to answer them in Java :


1. What is the difference between the start and run method in Java Thread? (answer)
This thread interview question is also asked as if the start() method eventually calls the run() method then why do you need to call the start() method, why not call the run() method directly. well, the reason is that because start method creates a new thread and calls the code written inside the run method on a new thread while calling the run method executes that code on the same thread. You can also see the article start vs run method in Java for more details.




2. Write code to avoid deadlock in Java where N threads are accessing N shared resources? (answer)
This is a classic Java multithreading interview question, which appears on almost every list of Java thread questions. This question is based on risks and issues faced by parallel programs without proper synchronization or incorrect synchronization.

This question explores the concept of looking and best practices on acquiring and releasing the lock on shared resources. By the way, it's been covered in many places as well and I suggest reading  How to prevent deadlock in Java, not only for a detailed answer to this Java multithreading question but also to learn how to prevent deadlock in Java.

thread interview questions for experience Java programmers





3. Which one is better to implement thread in Java? extending Thread class or implementing Runnable? (answer)
Well, this is another frequently asked question on any Java thread interview. Essentially these are two ways to implement Thread in Java, by extending the java.lang.Thread class or by implementing the java. lang.Runnable interface.

By extending the class you are using your chance to extend one any only one class as Java does not support multiple inheritances, by implementing a Runnable interface you can still extend another class. So extending Runnable or even Callable is a better choice. You can also see the Runnable vs Thread class in Java for more answers to these questions.

Given its simplicity and fact-based nature, this question mostly appears on either telephonic rounds or initial screening rounds. Key points to mention, while answering this question includes multiple Inheritance at the class level and separation of defining a task and execution of a task. Runnable only represents a task, while Thread represents both tasks and their execution.




4. What is Busy Spinning? Why will you use Busy Spinning as a wait strategy? (answer)
This is one of the advanced concurrency interview questions in Java and only asked to experienced and senior Java developers, with lots of concurrent coding experience under the belt. By the way, the concept of busy spinning is not new, but its usage with multi-core processors has risen recently.

The busy waiting is a wait strategy, where one thread waits for a condition to become true, but instead of calling the wait or sleep method and releasing the CPU, it just spins. This is particularly useful if the condition is going to be true quite quickly i.e. in a millisecond or microsecond.

The advantage of not releasing CPU is that all cached data and instruction remain unaffected, which may be lost, had this thread is suspended on one core and brought back to another thread. If you can answer this question, that rest assured of a good impression.


5. What is the difference between CountDownLatch and CyclicBarrier in Java? (answer)
CountDownLatch and CyclicBarrier in Java are two important concurrency utility which is added on Java 5 Concurrency API. Both are used to implement scenarios, where one thread has to wait for another thread before starting processing but there is a difference between them.

The key point to mention, while answering this question is that CountDownLatch is not reusable once the count reaches zero, while CyclicBarrier can be reused even after the barrier is broken.

You can also see my previous article difference between CyclicBarrier and CountDownLatch in Java for a more detailed answer to this concurrency interview question and a real-life example of where to use these concurrency utilities.




6. What is the difference between wait and sleep in Java? (method)
One more classic Java multithreading question from the telephonic round of interviews. The key point to mention while answering this question is to mention that wait will release the lock and must be called from the synchronized context, while sleep will only pause the thread for some time and keep the lock.

By the way, both methods throw IntrupptedException and can be interrupted, which can lead to some follow-up questions like, can we awake a sleeping or waiting for a thread in Java? You can also read a detailed answer on my post of the same title here.

thread interview questions with answers



7. How do you solve the producer-consumer problem in Java? (solution)
One of my favorite questions during any Java multithreading interview, Almost half of the concurrency problems can be categorized in the producer-consumer pattern. There are basically two ways to solve this problem in Java, One by using the wait and notify method and the other by using BlockingQueue in Java.  later is easy to implement and a good choice if you are coding in Java 5.

The key points to mention, while answering this question is the thread-safety and blocking nature of BlockingQueue and how that helps, while writing concurrent code.

You can also expect lots of follow-up questions including, what happens if you have multiple Producer threads or multiple consumers, what will happen if a producer is faster than a consumer thread, or vice-versa. You can also see this link for an example of how to code producer-consumer design in Java using a blocking queue



8. Why is ConcurrentHashMap faster than Hashtable in Java? (answer)
ConcurrentHashMap is introduced as an alternative to Hashtable in Java 5, it is faster because of its design. ConcurrentHashMap divides the whole map into different segments and only locks a particular segment during the update operation, instead of Hashtable, which locks the whole Map.

The ConcurrentHashMap also provides a lock-free read, which is not possible in Hashtable, because of this and lock striping, ConcurrentHashMap is faster than Hashtable, especially when the number of the reader is more than the number of writers.

In order to better answer this popular Java concurrency interview question, I suggest reading my post about the internal working of ConcurrentHashMap in Java.





9. What is the difference between the submit() and execute() method of Executor and ExecutorService in Java? (answer)
The main difference between submitting and execute methods from the ExecutorService interface is that the former returns a result in the form of a Future object, while the latter doesn't return a result. 

By the way, both are used to submit a task to thread pool in Java but one is defined in the Executor interface, while the other is added into the ExecutorService interface. This multithreading interview question is also asked in the first round of Java interviews.


10. How do you share data between two threads in Java? (answer)
One more Java multithreading question from the telephonic round of interviews. You can share data between threads by using shared objects or shared data structures like Queue. Depending upon, what you are using, you need to provide the thread-safety guarantee, and one way of providing thread-safety is using a synchronized keyword.

If you use concurrent collection classes from Java 5 e.g. BlockingQueue, you can easily share data without being bothered about thread safety and inter-thread communication. I like this thread question, because of its simplicity and effectiveness. This also leads further follow-up questions on issues that arise due to sharing data between threads e.g. race conditions.



11. What is ReentrantLock in Java? Have you used it before? (answer)
ReentrantLock is an alternative to the synchronized keyword in Java, it is introduced to handle some of the limitations of synchronized keywords. Many concurrency utility classes and concurrent collection classes from Java 5, including ConcurrentHashMap use ReentrantLock, to leverage optimization.

The ReentrantLock mostly uses an atomic variable and faster CAS operation to provide better performance. Key points to mention are the difference between ReentrantLock and synchronized keywords in Java, which includes the ability to acquire lock interruptibly, timeout feature while waiting for a lock, etc.

 ReentrantLock also gives the option to create a fair lock in Java. Once again a very good Java concurrency interview question for experienced Java programmers. Courses like Java Multithreading for Senior Engineering Interviews course from Educative. also help you to prepare better and answer to the point.

thread, concurrency and multi-threading questions for experienced Java programmers



12. What is ReadWriteLock in Java? What is the benefit of using ReadWriteLock in Java? (answer)

This is usually a follow-up question of previous Java concurrency questions. The  ReadWriteLock is again based upon the concept of lock striping, one of the advanced thread-safety mechanisms that advocates separating locks for reading and writing operations (see Java Concurrency in Practice Bundle by Heinz Kabutz for more details).

If you have noticed before, reading operation can be done without locking if there is no writer and that can hugely improve the performance of any application. The ReadWriteLock leverages this idea and provides policies to allow maximum concurrency level. Java Concurrency API also provides an implementation of this concept as ReentrantReadWriteLock.

Depending upon the Interviewer and experience of the candidate, you can even expect to provide your own implementation of ReadWriteLock, so be prepared for that as well.

Here is a nice diagram that clearly explains the working of read-write lock in Java:

Java Multithreading and Concurrency Interview Questions with Answers



These were some of my favorite interview questions based on multithreading and concurrent in Java. Threading and Concurrency is a big topic in Java and has lots of interesting, tricky, and tough questions but for starters and freshers, these questions certainly help to clear any thread interview in Java.

As I said, mentioning the key points are very important while answering questions on multithreading and concurrency.  I also suggest further reading Java Concurrency in Practice to learn more about locking, synchronization, concurrent collections, and concurrency utility classes to do well in core Java and multithreading interviews.



Related Java Interview Questions for Experienced Programmers:
Thanks for reading this article so far. If you found these Java Concurrency and Multithreading interview questions useful then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S. - If you are new to multithreading and concurrency and looking for a free course to learn multithreading concurrency in Java then I also suggest you check out the Free Java Multithreading course on Udemy. It's completely free and you just need a free Udemy account tot to join this course.

6 comments:

  1. One of the good question on multithreading, I have recently faced in a Java interview. After asking some basic question on thread and synchronization e.g. wait, notify, creating thread, stopping thread, thread pool etc. He asked, How do you reduce contention between threads? That's a really good question. As I was familiar with some techniques of reducing contention among multiple thread, I was quick to bring lock stripping concept, which splits a lock into multiple e.g. ReadWrite lock has separate lock for reading and writing. This can significantly reduce contention. Another way to reduce thread contention is minimizing use of synchronized keyword, instead using atomic and volatile variables.

    ReplyDelete
  2. Good question. Some answers are really good, especially with the busy spinning. Keep it up.

    ReplyDelete
  3. your answer to spining is not completely true. you completly ignore the java memory model which seems like an importand part here. it only gurantees you to see the correct value if accessed in sync block, or since 1.5 with some types using volatile. but second problem with not synchronizing is the as if serial semantic of jvm executions. this might lead you to situations where the reference to a object has already been set but the constructor has not been run. so even when your check for ref != null will be true you could get error.
    cheers, peter

    ReplyDelete
  4. Threads can be implemented by extending Thread class, implementing Runnable interface and Callable interface.

    If you want to return an value or throw an exception then use Callable otherwise use Runnable as extending Thread class limits the Class inheritance and also makes the process heavy.

    Below link can be useful if you want to find more:
    Different ways to implement Threads in Java

    ReplyDelete
  5. Few more questions
    - If you are asked to write code for synchronizing between two threads or 100 threads? which code will be harder to write and why?

    - Tell me three problems you usually face on concurrent environment.

    - What happend if you add task into Fixed thread pool and worker queue is full?

    - What happend if an exception is throw into a Thread?

    ReplyDelete
  6. http://fastthread.io/ tool is a self explanatory tool for analyzing thread dumps

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.