Monday 14 July 2014

Top 12 Java Thread, Concurrency and Multithreading Interview Questions and How to Answers them

Java concurrency and thread interview questions answers
Multithreading is an important feature of Java programming language, which means threads are also important part of any Java interview, in fact at beginner and fresher level Thread interview questions in Java are most difficult to answer. One reason for interview question related to multithreading and concurrency being difficult is confusion around how multiple thread works together and second is threads are genuinely a complicated topic to understand and use correctly. Mostly thread interview questions checks Java programmers knowledge on Java Thread API, Java concurrency API, issues related to multi-threading like Race Conditionthread-safety and deadlock. Some time multithreading and concurrency interview question also focus on parallel design pattern related stuff like solving producer consumer problem, implementing work steal pattern or solving dining philosopher problem in Java. In this article, we will take a look at different kinds of multithreading and concurrency questions asked in various interviews e.g. on telephonic or face to face interview, on written test, to both experienced and senior Java developers, and some tips to answer them correctly. Questions asked on telephonic or first round of interviews are tend to be easier and you must answer them to the point with keyword, which interviewer is expecting. On face to face interview, be prepare for different kinds of follow-up questions


Java Interview questions on Concurrency and multithreading

Java Thread interview question and answers for beginners freshers and experienced programmer
As I said, in this Java article, not only,  I will share some of the most commonly asked thread interview question at freshers and beginners level, like upto 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 tried to share answers of these interview questions on thread as well but I suggest you do some research and learn the topic well to answer any followup questions, which comes due to your response of these thread questions in Java. Anyway here are my collection of Java thread interview question and how to answers them in Java :

1) What is difference between start and run method in Java Thread?
This thread interview question is also ask as if start() method eventually callrun() method than why do you need to call start() method, why not callrun() method directly. well reason is that because start method creates a new thread and call the code written inside run method on new thread while calling run method executes that code on same thread. see 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?
This is a classic Java multithreading interview questions, which appears on almost every list of Java thread questions. Thisquestion is based on risk and issues faced by parallel programs without proper synchronization or incorrect synchronization. This question explores concept of looking and best practices on acquiring and releasing lock on shared resource. By the way it's been covered on many places as well and I suggest reading  How to prevent deadlock in Java, not only for detailanswer of this Java multithreading question but also to learn how to prevent deadlock in Java.

3) Which one is better to implement thread in Java ? extending Thread class or implementing Runnable?
Well this is another frequently asked questions on any Java thread interview. Essentially these are two way to implement Thread in Java and by extending class you are using your chance to extend one any only one class as Java does not support multiple inheritance, by implementing Runnable interface you can still extend another class. So extending Runnable or even Callable is better choice. see Runnable vs Thread class in Java for more answers on this questions. Given it's simplicity and fact based nature, this question mostly appear on either telephonic round or initial screening rounds. Key points to mention, while answering this question includes, multiple inheritance at class level and separation of defining a task and execution of task. Runnable only represent a task, while Thread represent both task and it's execution.

4) What is Busy Spinning? Why you will use Busy Spinning as wait strategy?
This is really an advanced concurrency interview questions in Java and only asked to experienced and senior Java developers, with lots of concurrent coding experience under belt. By the way concept of busy spinning is not new, but it's usage with multi core processor has risen recently. It's a wait strategy, where one thread wait for a condition to become true, but instead of calling wait or sleep method and releasing CPU, it just spin. This is particularly useful if condition is going to be true quite quickly i.e. in millisecond or micro second. Advantage of not releasing CPU is that, all cached data and instruction are remained 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 assure of a good impression.

5) What is difference between CountDownLatch and CyclicBarrier in Java?
CountDownLatch and CyclicBarrier in Java are two important concurrency utility which is added on Java 5 Concurrency API. Both are used to implement scenario, where one thread has to wait for other thread before starting processing but there is difference between them. Key point to mention, while answering this question is that CountDownLatch is not reusable once count reaches to zero, while CyclicBarrier can be reused even after barrier is broken. You can also see my previous articledifference between CyclicBarrier and CountDownLatch in Java for more detailed answer of this concurrency interview questionand a real life example of where to use these concurrency utilities.

6) Difference between wait and sleep in Java?
One more classic Java multithreading question from telephonic round of interviews. Key point to mention while answering this question is to mention that wait will release lock and must be called from synchronized context, while sleep will only pause thread for some time and keep the lock. By the way, both throws IntrupptedException and can be interrupted, which can lead to some followup questions like, can we awake a sleeping or waiting thread in Java? You can also read detailed answer on my post of same title here.

7) How do you solve producer consumer problem in Java?
One of my favorite questions during any Java multithreading interview, Almost half of the concurrency problems can be categorized in producer consumer pattern. There are basically two ways to solve this problem in Java, One by using wait and notify method and other by using BlockingQueue in Java. later is easy to implement and good choice if you are coding in Java 5. Key points to mention, while answering this question is threadsafety and blocking nature of BlockingQueue and how that helps, while writing concurrent code. You can also expect lots of followup questions including, what happen if you have multiple producer or multiple consumer, what will happen if producer is faster than consumer thread or vice-versa. You can also see this link for example of how to code producer consumer design in Java using blocking queue


8) Why ConcurrentHashMap is faster than Hashtable in Java?
ConcurrentHashMap is introduced as alternative of Hashtable in Java 5, it is faster because of it's design. ConcurrentHashMap divides whole map into different segments and only lock a particular segment during update operation, instead of Hashtable, which locks whole Map. ConcurrentHashMap also provides lock free read, which is not possible in Hashtable, because of this and lock striping, ConcurrentHashMap is faster than Hashtable, especially when number of reader is more than number of writers. In order to better answer this popular Java concurrency interview questions, I suggest reading my post about internal working of ConcurrentHashMap in Java.

9) What is difference between submit() and execute() method of Executor and ExecutorService in Java?
Main difference between submit and execute method from ExecutorService interface is that former return a result in form of Future object, while later doesn't return result. By the way both are used to submit task to thread pool in Java but one is defined in Executor interface,while other is added into ExecutorService interface. This multithreading interview question is also asked at first round of Java interviews.

10) How do you share data between two threads in Java?
One more Java multithreading question from telephonic round of interview. You can share data between thread by using shared object or shared data structures like Queue. Depending upon, what you are using, you need to provide thread-safety guarantee, and one way of providing thread-safety is using 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 it's simplicity and effectiveness. This also leads further follow-up questions on issues which arises due to sharing data between threads e.g. race conditions. 

11) What is ReentrantLock in Java? Have you used it before?
ReentrantLock is an alternative of 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, includingConcurrentHashMap uses ReentrantLock, to leverage optimization. ReentrantLock mostly uses atomic variable and faster CAS operation to provides better performance. Key points to mention is difference between ReentrantLock and synchronized keyword in Java, which includes ability to acquire lock interruptibly, timeout feature while waiting for lock etc. ReentrantLock also gives option to create fair lock in Java.Once again a very good Java concurrency interview question for experienced Java programmers.

12) What is ReadWriteLock in Java? What is benefit of using ReadWriteLock in Java?
This is usually a followup question of previous Java concurrency questions. ReadWriteLock is again based upon lock striping by providing separate lock for reading and writing operations. If you have noticed before, reading operation can be done without locking if there is no writer and that can hugely improve performance of any application. ReadWriteLockleverage this idea and provide policies to allow maximum concurrency level. Java Concurrency API also provides an implementation of this concept as ReentrantReadWriteLock. Depending upon Interviewer and experience of candidate, you can even expect to provide your own implementation of ReadWriteLock, so be prepare for that as well.

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 question but for starters and freshers these questions certainly help to clear any thread interview in Java. As I said, mentioning key points are very important while answering questions on multithreading and concurrency. I also suggest further reading on locking, synchronization, concurrent collections and concurrency utilities classes to do well in core Java and multithreading interviews.

No comments:

Post a Comment