Java Multithreading Interview Questions And Answers

In this post there is a collection of Java multithreading interview questions and answers which’ll be helpful for interview preparation.

Java multithreading interview questions

  1. What is multithreading?
    A program can have more than one sub-tasks running independently, these sub-tasks are known as threads and a program can have many such threads running making it a multi-threaded program. Java has built-in support for multi-threaded programming.
    Read more about Multithreading here.
  2. What are the advantages of multithreading?
    In a program you can have a task that waits for some resource or event, rather than making your whole program tied to that task and make the whole program unresponsive, you can create a separate thread for that task so that it can independently. That is one of the advantages of multi-threading.
    By having multiple thread running concurrently CPU usage is optimum and the performance of the application is improved.
    Since threads are light-weight and share heap memory, any time taking task can be performed by multiple threads rather than a single thread to increase the throughput by sharing CPU cycle and without using much memory.
    Read more about Multithreading here.
  3. How is thread created in Java?
    Thread in Java can be created by-

    • By implementing Runnable interface.
    • By Extending Thread class.

    Whichever of these two ways is chosen by you to create a thread in Java you need to override run() method and provide the code that will run in that thread.
    Read more about how to create thread in Java here.

  4. What is the process for running a created thread?
    Once you have the instance of the created thread-

    • Call start method on the created thread object – thread.start();
    • Once the thread is started run method will be executed.

    Read more about how to create and start thread in Java here.

  5. Difference between thread and process in Java?
    In concurrent programming there are two types of multitasking-

    • Process based multitasking.
    • Thread based multitasking.

    A process has a self-contained execution environment. A process has its own run-time resources like memory space. Threads exist within a process — every process has at least one. Threads share the process’s resources, including memory and open files.

    Processes are heavyweight tasks running in their own allocated memory space. Threads are lightweight spawned with in a process and share its memory.
    Read more about difference between thread and process in Java here.

  6. What is the preferred way to create thread – Extending Thread class or implementing Runnable?
    Though both of these methods are equal in the way that thread created by using one way is no different from the thread created using the other way but one thing that you have to keep in mind is that Java does not support multiple inheritance i.e. any Java class can extend at most one class.
    If your class extend Thread class to create a thread then the class can’t extend any other class. That is one of the disadvantages of using Thread class to create a thread.
  7. What is the thread life cycle or Different thread states in Java?
    Once you create a thread in Java a thread can be in one of the following states-
    NEW– A thread in Java is in new state when it is created but not yet started
    RUNNABLE– A thread transitions to a runnable state when start() method is called on the thread object.
    BLOCKED– A running thread can change state to blocked state and become temporarily inactive when it is waiting for a monitor lock.
    WAITING– A running thread may move to waiting state by calling either Object.wait() or Thread.join() method.
    TIMED_WAITING– A thread is in timed waiting state when it calls sleep, wait or join method with a timed out parameter.
    TERMINATED– A thread that has completed execution goes into terminated state.
    Read more about thread cycle in Java here.
  8. How can you get thread state in Java code?
    You can get thread state in Java by calling getState() method on the thread instance which returns a Thread.State enum.
    Read more about different thread states in Java here.
  9. What is thread priority in Java?
    Every thread in Java has a priority assigned to it. When you create a thread in Java it inherits the priority of the thread that created it.
    In a multi-threaded environment, the order in which threads will get CPU cycle is decided by the thread scheduler and it uses thread priority to decide that order.
    Read more about different thread priorities in Java here.
  10. What is the thread priority range in Java?
    Java thread priority is in the range 1 to 10 where 1 being the lowest and 10 being the highest thread priority in Java.In Java Thread class there are three static int fields defining min, max and default priority of a thread.
    MAX_PRIORITY– The maximum priority that a thread can have. Its value is 10.
    MIN_PRIORITY– The minimum priority that a thread can have. Value of this field is 1.
    NORM_PRIORITY– The default priority that is assigned to a thread. Its value is 5.
    Read more about different thread priorities in Java here.
  11. How to change the thread’s priority and check the thread’s priority in Java?
    Thread’s priority can be changed at any time after its creation using the setPriority() method of the Thread class. If you want to check the thread’s priority you can check it using getPriority() method of the Thread class.
  12. When you start any Java application which is the first thread to start?
    When a Java program starts one thread starts running immediately that thread is known as main thread in Java.
    Additional threads spawned in your program will inherit some of the properties from the main thread like thread priority, created thread is a daemon thread or not.
    Read more about main thread in Java here.
  13. What is a daemon thread in Java?
    Daemon thread in Java is a thread that runs in background to perform some tasks for the program as long as the program is running.
    Read more about daemon thread in Java here.
  14. How is daemon thread created in Java?
    Any thread created by a daemon thread is automatically a daemon thread.If you want to mark a thread as a daemon thread that can be done using setDaemon(boolean on) method of the Thread class in Java. By calling setDaemon(true); on a thread instance you can make that thread a daemon thread.
    Read more about daemon thread in Java here.
  15. Is it possible to start a thread twice in Java?
    A Thread can only be started once, trying to start the same thread again in Java will throw IllegalThreadStateException.
    Read more about can we start a thread twice in Java here.
  16. What if run() method of the thread is called directly instead of calling start() method?
    If run method is called directly on a thread then no new thread will actually be started. The logic you have written in the run() method will be executed with in the context of the current thread.
    Read more about Can we directly call run() method instead of calling start() method in Java here.
  17. Can we override the start() method in Java?
    Yes start() method can be overridden in Java if you have some logic to be executed before calling the run() method.
    One condition is that you should always call super.start() method from your overridden start() method. Failing to call super.start() will mean run() method won’t be called.
    Read more about Can we override start() method in Java here.
  18. What is context switching in multi-threading?
    Context switching in terms of multi-threading is the switching of CPU from one thread to another.
    When a thread is preempted to execute another thread, thread state of the preempted thread has to be stored where as the thread which is getting executed has to restore its state.
  19. How does inter-thread communication happens in Java multi-threading?
    In Java multi-threading there are 3 methods for facilitating communication among multiple threads.

    • wait() method– wait() method causes the current thread, holding the object’s lock, to place itself into waiting state.
    • notify() method– Wakes up a single thread that is waiting on this object’s monitor.
    • notifyAll() method– Wakes up all threads that are waiting on this object’s monitor rather than a single thread.

    Read more about wait(), notify() and notifyAll() methods in Java here.

  20. What is a spurious wakeup?
    A waiting thread can wake up without being notified, interrupted, or timing out this is known as spurious wakeup. Applications must guard against it by putting a call to wait() within a loop that checks the condition on which the thread is waiting.

  21. Write Producer-consumer program in Java using wait-notify methods.
    See Producer-consumer program in Java using wait-notify methods here.
  22. Why wait(), notify() and notifyAll() methods are in Object class?
    These methods wait(), notify() and notifyAll() work with the lock (monitor) which is associated with the object. The object whose lock is held is used for the communication among the threads.
    That’s why wait(), notify() and notifyAll() methods are in Object class.
    See detailed explanation of Why wait(), notify() and notifyAll() methods are in Object class here.
  23. why wait(), notify() and notifyAll() methods in Java must be called from a synchronized method or block?
    wait() method causes the current thread to give up monitor and go into waiting state. Thread acquires Object’s lock only when it is executing in a synchronized context. That is why wait() method has to be used only in synchronized context.When object’s notify() or notifyAll() method is called it is a signal for a single thread or all the threads to wake up and contend for the monitor. So notify and notifyAll methods can only be called from a place where the thread is leaving the lock on the object and again that place is synchronized method or block.
    See detailed explanation of why wait(), notify() and notifyAll() methods in Java must be called from a synchronized method or block here.
  24. What does synchronized keyword in Java do?
    In a multi-threaded environment if you have a critical section in you code where you are modifying a shared resource you would like the access to that critical section restricted so that at any given time only a single thread can access the critical section code and use the shared resource. The process by which you can achieve this is called synchronization in Java and you will use synchronized keyword in Java for synchronization.
    Read more about synchronized keyword in Java here.
  25. How does synchronization in Java works?
    Every object in Java has a single lock (also called monitor) associated with it. When a thread enters a synchronized method or synchronized block it acquires that lock. All other threads attempting to execute the same code (in synchronized method or synchronized block) have to wait for the first thread to finish and release the lock.
    Read more about how synchronization works in Java here.
  26. What is synchronized statement or synchronized block in Java?
    Rather than synchronizing the whole method you can only synchronize the statements (critical section) in the method that are modifying the shared resource. That helps in improving the performance as threads can only execute the code with in synchronized context sequentially. By minimizing the code with in synchronized context you reduce the possibility of sequential execution of the threads.
    Read more about synchronized block in Java here.
  27. What is static synchronization in Java?
    If there are more than one object of the same class then two separate threads can acquire locks of these two objects and enter the synchronized method or synchronized block with those separate locks at the same time.If that is not what you want then you need static synchronization in Java where synchronization happens at the class level not at instance level.
    Read more about static synchronization in Java here.
  28. How can you ensure that you start execution of the main thread only after execution of the other threads started from the main thread finishes?
    That can be done by calling join() method on the threads that are started.
    join() method waits until the thread on which it is called terminates.
    Read more about join() method in Java here.
  29. How can you check if the thread is still alive or not?
    By using isAlive() method. This method tests if this thread is alive. Method returns true if thread is alive otherwise it returns false.
    Read more about isAlive() method in Java here.
  30. What is thread group in Java?
    All threads in Java belong to a thread group. When a thread is created it is put into a thread group specified either by you or to the same group as the thread that created it if no thread group is explicitly specified.
    When the main thread is started for the Java application, it is put into a group called main.
    Read more about thread group in Java here.
  31. How can you interrupt a thread?
    In Java Thread class there is a method interrupt() which interrupts the calling thread.
    Read more about thread interruption in Java here.
  32. How can you pause a running thread?
    You can pause a running thread by using sleep() method. Thread.sleep method in Java causes the currently executing thread to suspend execution for a specified period.
    Read more about sleep method in Java here.
  33. If sleep() method is called with in the synchronized context does the sleeping thread release the lock?
    No the lock held by the thread is not released.
  34. What is race condition in multi-threading?
    Race condition in Java may occur when two or more threads try to access a shared object. If all the threads are just reading a shared object that poses no problem but modifying or writing a value may lead to incorrect results because of race condition.
    Read more about race condition in Java here.
  35. How to avoid race condition in Java?
    You need to restrict access to the critical section for that you can synchronize the access to the critical section by using synchronized method or block. You can also use implementations of lock provided in concurrency package.
    Read more about race condition in Java here.
  36. What is deadlock in multi-threading?
    In a multi-threaded environment there may come a situation when one thread is waiting for a resource that is locked by another thread, which in turn is waiting for another thread and so on until this dependency loops back to the first waiting thread. Thus all the threads are waiting for each other to release the resources to make any further progress and blocked forever in the process. This scenario is called deadlock in multi-threading.
    Read more about deadlock in Java here.
  37. Write a Java program to create deadlock?
    See a Java program to create deadlock here.
  38. How to detect deadlock in Java or How to get thread dump in Java?
    For detecting deadlock in your code you can get a thread dump of the application and analyze it.
    You can use jstack utility to get a thread dump by providing the pid of the Java application. That pid can be obtained by running jps command.
    See example of getting a thread dump and analyzing it for deadlock here.
  39. What is yield() method in Java?
    yield() method is just a hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler can ignore this hint too.
    Read more about yield() method in Java here.
  40. What is ThreadLocal class in Java?
    ThreadLocal class in Java provides thread local variables where each thread has its own, independently initialized copy of the variable.
    That way you can avoid sharing of data and avoid using synchronization.
    Read more about ThreadLocal class in Java here.
  41. What is volatile keyword in Java?
    Declaring a variable as volatile ensures that value of the variable is always read from the main memory and not cached. This ensures that thread don’t have a stale value cached by the processor and always get the correct value from the main memory.
    Read more about volatile keyword in Java here.
  42. What is thread starvation in multi-threading?
    If a thread is unable to gain regular access to shared resources and is unable to make progress it is called thread starvation in multi-threading.
    There may be a scenario that other threads are gaining access to the synchronized method or block by getting the monitor where as few threads are not able to get the lock thus the access to shared resource.
    Read more about thread starvation in Java here.
  43. What is livelock in multi-threading?
    If two or more threads are busy responding to the action of each other and unable to make further progress in the process that is known as livelock in multi-threading.
    In case of livelock threads are not blocked as in the case of deadlock. Threads are active but they are busy responding to each other thus not making any progress.
    Read more about livelock in Java here.

That’s all for the topic Java Multithreading Interview Questions And Answers. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.