Java interview questions on multithreading are must to learn for a Java developer. Multithreading means multiple threads running in parallel. Multithreading is known as a process of executing the multiple threads simultaneously. You need to keep on practicing the Java multithreading programming exercises and practice problems, if you want to succeed in Java advanced multithreading and concurrency interview round.
Multithreading interview questions are questions consists of Java threads, processes, Multithreading, locks, deadlock and concurrency apis concepts. For Java freshers, high level knowledge on core java multithreading, is tested in interview. For multiple years experienced developers, in depth details are expected. Detailed study of Concurrency APIs is required to clear Java multithreading and concurrency interview.
- Java interview questions and answers multithreading
- 1. What is a process and thread in java?
- 2. What is the difference between Thread and Process?
- 3. What is thread life cycle in java?
- 4. How to set thread priority in java?
- 5. Is it possible to start a thread twice?
- 6. What is a daemon thread?
- 7. What is a shutdown hook?
- 8. What is intrinsic lock?
- 9. What is deadlock?
- 10. what is race condition and how to avoid it?
- 11. What is volatile keyword in java?
- 12. What is synchronization in java?
- 13. What is difference between sleep and yield methods in java?
- 14. What is difference between class level lock and object level lock?
- 15. What is difference between Callable and Runnable interface?
- 16. What is the difference between preemptive scheduling and time slicing?
- 17. What is thread pool in java?
- 18. What is concurrency api in java?
- 19. What is lock interface in java concurrency api?
- 20. What is blockingqueue ?
- Conclusion
Java interview questions and answers multithreading
1. What is a process and thread in java?
Process: A process features a self-contained execution environment. A process generally features a complete, private set of basic run-time resources; especially , each process has its own memory space.
Thread: A thread is sometimes called as lightweight processes. Both processes and threads provide an execution environment, but a new thread creation requires fewer resources than a new process creation. Threads exist within a process — every process has a minimum of one. Threads share the resources of processes, including open files and memory.
2. What is the difference between Thread and Process?
In Java, processes correspond to a running JVM (Java Virtual Machine) whereas threads live with-in the JVM and may be created and stopped by the Java application dynamically at runtime. Processes have their own address while Thread share the address space of the method that created it. Thread has its own stack while in process all threads share a standard system resource like heap memory.
3. What is thread life cycle in java?
A thread goes through various states in its full life cycle. for instance , a thread is born, started, runs, then dies. A thread are often in one among the subsequent thread states.
NEW: A thread that has not yet started or running is in New state.
RUNNABLE: A thread executing or running within the Java virtual machine is in Runnable state.
BLOCKED: A Blocked state occurs whenever a thread tries to accumulate lock on some object and the other thread is already holding the lock thereon object. So, a blocked thread is expecting other thread to release the lock and it can’t be interrupted.
WAITING: A thread that’s waiting indefinitely for another thread to perform a specific action is in this state. A thread will enter in waiting state when it calls wait() or join() method. The thread will remain within the waiting state until the other thread calls the notify() or notifyAll() methods.
TIMED_WAITING: A runnable thread enters the timed_waiting state for a specified interval of time. A thread during this state transitions back to the runnable state when the interval expires or when the event it’s expecting occurs.
TERMINATED: A thread enters the terminated state when it exits or completes its task.
4. How to set thread priority in java?
The priority of a java thread can be set by using the method setPriority(int). To set the priority to the maximum value, you can use the constant Thread.MAX_PRIORITY and to set the value to the minimum you use the constant Thread.MIN_PRIORITY . If you do not explicitly define priority of a thread then default value is used by JVM which is Thread.NORM_PRIORITY.
5. Is it possible to start a thread twice?
A thread cannot be restarted, as after starting a thread it gets executed and gets terminated. If we attempt to restart a thread, second invocation of start() will throw an exception IllegalThreadStateException.
6. What is a daemon thread?
A daemon thread in Java is a low priority thread, it provides the background services and support to the user threads. A daemon thread’s execution state is not evaluated by JVM when JVM all user threads (in contrast to daemon threads) are terminated. The daemon threads can be used to built monitoring functionality as JVM itself stops the thread as soon as all related user threads are terminated.
7. What is a shutdown hook?
A shutdown hook is a thread that’s invoked implicitly before JVM shuts down. So you can use it to perform the clean up activites or persist the state when JVM shuts down abruptly or normally. You can add shutdown hook by using the subsequent method:
Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // your code goes here } });
8. What is intrinsic lock?
An intrinsic lock (or monitor lock) is an implicit internal entity associated with each instance of the objects. The intrinsic lock enforces the exclusive access to an object’s state.
A synchronized method acquires the intrinsic lock for the method’s object and releases it when the method returns or exits. Even if the method throws any exception, the intrinsic lock is always released.
9. What is deadlock?
Deadlock is a particular situation in which a thread is waiting for a resource which is already held by another waiting thread. Neither of the thread gets executed and both kept waiting for infinite time. Deadlock is a complicated situation and it can block our application from further execution. Example:
Thread T1: takes lock of resource A and waits for resource A to be released
Thread T2: takes lock of resource B and waits for resource B to be released
10. what is race condition and how to avoid it?
A race condition is a situation the outcome of some multithreaded implementation depends on the sequence or timing of the threads. In multithreaded environment, when multiple threads try to access a shared resource simultaneously.
Race conditions can be avoided by proper use of thread synchronization in critical sections.
11. What is volatile keyword in java?
Volatile keyword is a keyword that can only be used with variables. When you make a variable as volatile, then all threads fetches its latest value directly from the memory and cache is never used. This makes sure that all threads have consistently updated value of shared variables.
12. What is synchronization in java?
Synchronization in java is a capability to control the access of multiple threads to any shared resource. When one or more threads try to perform the same task, there is a great possibility of an erroneous result, So to avoid this issue, Java uses the synchronization process which allows only a single thread to be executed at any time.
13. What is difference between sleep and yield methods in java?
sleep() method takes duration as argument and ensures that the present thread suspends its execution for the required time. When sleep() method is called current thread will certainly go to sleep for the required time. sleep() method throws InterruptedException if sleeping thread is interrupted so call to sleep() method should either be enclosed in try-catch block or it should be declared using throws clause.
yield() method is simply a hint to the scheduler that the present thread is willing to yield its current use of a processor. Scheduler can even ignore this hint to yield. In case of yield() method first of all it’s just a hint which may be ignored, even if the present thread yields the CPU it can start running again if there’s no other thread with an equivalent or more thread priority. yield() method doesn’t throw InterruptedException.
14. What is difference between class level lock and object level lock?
Class level lock is achieved by using the Static Synchronized method. If a thread wanted to execute a static synchronized method on given class, then that thread will require a class level lock. Once a thread acquires the class level lock, then it is allowed to execute that class’s any static synchronized method.
Object level lock is achieved only by synchronized methods. Object level lock is achieved to limit same object to work through different thread,where as class level lock is achieved to limit any object to work .
If a thread wanted to execute a synchronized method on a given object. First of all, it has to acquire the lock of that object. Once a thread gets the object lock then it is allowed to execute any synchronized method on that locked object.
15. What is difference between Callable and Runnable interface?
The Runnable interface is an interface which should be implemented by any class whose instances are intended to be executed by a thread. the class must implement a method called run, with no arguments. This interface is meant to provide a standard protocol for objects that wish to execute code while they’re active. The Runnable interface should be used if you’re only planning to override the run() method and no other Thread methods.
The Callable interface is an interface almost like Runnable, therein both are designed for the classes whose instances are potentially executed by another thread. The implementation of Callable interface returns a result and should throw an exception, the Implementors define one method with no arguments called call.
A Runnable, however, doesn’t return a result and can’t throw a checked exception.
16. What is the difference between preemptive scheduling and time slicing?
Preemptive scheduling is a general term used for scheduling algorithms. the highest priority task executes until it enters the waiting or dead states or a better priority task comes into existence. Algorithms supported preemptive scheduling are: Round Robin (RR), Priority (preemptive version), Shortest Remaining Time First (SRTF), etc.
Time slicing scheduling is the one sort of preemptive based scheduling algorithm, a task executes for a predefined slice of time then reenters the pool of ready tasks. The scheduler then determines which task should execute next, supported priority and other factors.
17. What is thread pool in java?
Java Thread pool represents a group of worker threads that are expecting the work and can be reused repeatedly .
In thread pool, there a group is created with fixed size threads. A thread from the thread pool is selected and pulled out, then a job is assigned to it by the service provider. After completion of the work , thread is returned within the thread pool again.
18. What is concurrency api in java?
Concurrency means the ability to run several programs or several parts of a program in parallel. The Concurrency apis in Java are present in package java.util.concurrent and contains many useful classes for handling concurrent programming. Since Java 5 the Concurrency API has been enhanced with every new Java release and even Java 8 provides new classes and methods for handling concurrency.
19. What is lock interface in java concurrency api?
A java.util.concurrent.locks.Lock is a thread synchronization mechanism a bit like synchronized blocks. A Lock is, however, more sophisticated and more flexible than a synchronized block. Since Lock is an interface, you would like to use one among its implementations to use a Lock in your applications. ReentrantLock is one of such implementation of Lock interface.
20. What is blockingqueue ?
A blocking queue is a queue that blocks once you attempt to dequeue from it and therefore the queue is empty, or if you are trying to enqueue items to that and also the queue is already full. A thread trying to dequeue from an empty queue is blocked until another thread inserts an item into the queue. A thread trying to enqueue an item in a very full queue is blocked until another thread makes space within the queue, either by dequeuing one or more items or clearing the queue completely.
Conclusion
These were few mostly asked Java Interview Questions On Multithreading. There are lots of related areas to be covered, as during interviews one given answer, leads to another questions and create chain of questions. So you really need to practice Java in depth, if you want to succeed.