Java Multi-Threading and Concurrency Interview Questions with Answers

Multithreading or Concurrency is one of the popular topic in java interview questions. Here I am listing down most of the important questions from interview perspective, but you should have good knowledge on java threads to deal with follow up questions.

Java Multi-Threading Interview Questions

  1. What is the difference between Process and Thread?
  2. What are the benefits of multi-threaded programming?
  3. What is difference between user Thread and daemon Thread?
  4. How can we create a Thread in Java?
  5. What are different states in lifecycle of Thread?
  6. Can we call run() method of a Thread class?
  7. How can we pause the execution of a Thread for specific time?
  8. What do you understand about Thread Priority?
  9. What is Thread Scheduler and Time Slicing?
  10. What is context-switching in multi-threading?
  11. How can we make sure main() is the last thread to finish in Java Program?
  12. How does thread communicate with each other?
  13. Why thread communication methods wait(), notify() and notifyAll() are in Object class?
  14. Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block?
  15. Why Thread sleep() and yield() methods are static?
  16. How can we achieve thread safety in Java?
  17. What is volatile keyword in Java
  18. Which is more preferred – Synchronized method or Synchronized block?
  19. How to create daemon thread in Java?
  20. What is ThreadLocal?
  21. What is Thread Group? Why it’s advised not to use it?
  22. What is Java Thread Dump, How can we get Java Thread dump of a Program?
  23. What is Deadlock? How to analyze and avoid deadlock situation?
  24. What is Java Timer Class? How to schedule a task to run after specific interval?
  25. What is Thread Pool? How can we create Thread Pool in Java?

Java Concurrency Interview Questions

  1. What is atomic operation? What are atomic classes in Java Concurrency API?
  2. What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?
  3. What is Executors Framework?
  4. What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?
  5. What is Callable and Future?
  6. What is FutureTask class?
  7. What are Concurrent Collection Classes?
  8. What is Executors Class?
  9. What are some of the improvements in Concurrency API in Java 8?

Java Multi-Threading Questions Answers

  1. What is the difference between Process and Thread?

    A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

  2. What are the benefits of multi-threaded programming?

    In Multi-Threaded programming, multiple threads are executing concurrently that improves the performance because CPU is not idle incase some thread is waiting to get some resources. Multiple threads share the heap memory, so it’s good to create multiple threads to execute some task rather than creating multiple processes. For example, Servlets are better in performance than CGI because Servlet support multi-threading but CGI doesn’t.

  3. What is difference between user Thread and daemon Thread?

    When we create a Thread in java program, it’s known as user thread. A daemon thread runs in background and doesn’t prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from daemon thread is also a daemon thread.

  4. How can we create a Thread in Java?

    There are two ways to create Thread in Java – first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread Class. Read this post to learn more about creating threads in java.

  5. What are different states in lifecycle of Thread?

    When we create a Thread in java program, its state is New. Then we start the thread that change it’s state to Runnable. Thread Scheduler is responsible to allocate CPU to threads in Runnable thread pool and change their state to Running. Other Thread states are Waiting, Blocked and Dead. Read this post to learn more about life cycle of thread.


Java Concurrency Interview Questions Answers

  1. What is atomic operation? What are atomic classes in Java Concurrency API?

    Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.

    int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.

    To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization. Go to this article to learn more about atomic concurrent classes.

  2. What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?

    Lock interface provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.
    The advantages of a lock are

    • it’s possible to make them fair
    • it’s possible to make a thread responsive to interruption while waiting on a Lock object.
    • it’s possible to try to acquire the lock, but return immediately or after a timeout if the lock can’t be acquired
    • it’s possible to acquire and release locks in different scopes, and in different orders

    Read more at Java Lock Example.

  3. What is Executors Framework?

    In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface.

    The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.

    Creating a lot many threads with no bounds to the maximum threshold can cause application to run out of heap memory. So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused. Executors framework facilitate process of creating Thread pools in java. Check out this post to learn with example code to create thread pool using Executors framework.

  4. What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?

    java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

    BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.

    BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.

    BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem.
    Check this post for producer-consumer problem implementation using BlockingQueue.

  5. What is Callable and Future?

    Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

    Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
    Check this post for Callable Future Example.

  6. What is FutureTask Class?

    FutureTask is the base implementation class of Future interface and we can use it with Executors for asynchronous processing. Most of the time we don’t need to use FutureTask class but it comes real handy if we want to override some of the methods of Future interface and want to keep most of the base implementation. We can just extend this class and override the methods according to our requirements. Check out Java FutureTask Example post to learn how to use it and what are different methods it has.

  7. What are Concurrent Collection Classes?

    Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException.

    Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates.
    Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, check this post to learn how to avoid ConcurrentModificationException when using iterator.

  8. What is Executors Class?

    Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.

    Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations.

  9. What are some of the improvements in Concurrency API in Java 8?

    Some important concurrent API enhancements are:

    • ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
    • CompletableFuture that may be explicitly completed (setting its value and status).
    • Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.

    Recommended Read: Java 8 Features

That’s all for Java Thread and Concurrency interview questions, I have been adding more to this list. So bookmark the post for future reference.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
SSL Begineers Guide eBook Free Download Now
Exclusive Offer: Citrix™ Whitepaper on Denial of Service Attack Download Now