Java / Java Multithreading
1. Multitasking.
We often multi task, listing to music while working or driving; Browsing internet while waiting for a download to complete. Even every computer application do things parallel. An email software will be downloading new emails from the server while you are reading an already downloaded email, archi...
2. Multiprogramming/Multiprocessing.
A computer or device running more than one application at the given time. For e.g. running mp3 player application while reading a blog using internet browser. Here mp3 player application and browser are two different programs/applications(or multiple programs) running at the same time.
3. Basic units of execution in concurrent programming.
There are two basic units of execution. processes and threads
4. Is concurrency possible on simple single processor systems without multiple processors?
Yes, it is.
5. Define Processes.
Processes also known as programs or applications has its self-contained execution environment with its own memory space. Process is considered to be heavyweight processes.
6. Define Threads.
These are lightweight processes, has its execution environment , requires minimal resource to create than Process. Threads are subset of process, each process has at least one thread and it shares process' memory and resources.
7. What is the default thread of every Java application?
"main" thread. This thread can create additional threads. ackage com.tutorials.threading; public class MainThread { public static void main (String [] args) { System.out.println(Thread.currentThread().getName()); } }
8. When does Thread Interference occur?
When two threads trying to act on the same data, latest thread wins and the first thread update is lost.
9. Thread Objects.
Each thread in java is an instance of the class java.lang.Thread.
10. How do you create a Thread?
Implement Runnable interface and its only method run(), which will have the code to be executed by the thread. The object for the class that implements the Runnable interface is passed as an argument to the Thread constructor as explained below. An application can use the Executor framework, in o...
11. Which approach is recommended?
Implementing the Runnable interface is used when your class need to extend another class. When you extend Thread class, you can not extend another class. so Implementing the Runnable interface is preferred.
12. Does Thread class implements Runnable?
Yes.
13. What is the signature of Thread run() method?
public void run() {}
14. Define synchronization.
Synchronization means allowing only one thread at a time to access an object. Synchronization control the access the multiple threads to a shared resources. Without thread synchronization, one thread can modify a shared variable while another thread is working on the same variable, which leads to...
15. Can a thread be interrupted when it is in sleep?
yes.
16. Does sleep() method throws any Exception?
Yes. We need to handle java.lang.InterruptedException. The Sleeping thread throws InterruptedException when another thread intercepts its sleep.
17. Can the start method be called twice on the same Thread? (OR) Can the start() method invoked again on the same thread object after start() been called first time?
No. It will throw IllegalThreadStateException during runtime. We need to create a new thread object and invoke start() method only once. A thread may not be restarted once it has completed execution as it goes to dead state.
18. Why do we call Thread.start() method which in turns calls run method?
run() method can be called directly however it will not be executing the method under new thread instead the method gets run on current thread. When start() method is called it invokes run() by create a new Thread. package com.tutorials.threading; public class ThreadExtended extends Thread { publ...
19. Consumer Producer problem.
package com.tutorials.threading; public class ConsumerProducerProblem { int value = 0 ; volatile boolean hasChanged = false ; public void produce( int value) throws InterruptedException { while (hasChanged == true ) { } System.out.println( "Value set:" + value); this.value = value; hasChanged = t...
20. Difference between Thread.interrupted() and Thread.isInterrupted().
Thread.interrupted() Thread.isInterrupted() interrupted() is a static method of Thread class and checks the current running thread if it is interrupted. isInterrupted() is an instance method which checks the Thread object for its interrupt status that it is called on. Calling interrupted() clears...
21. Give few example from Java API that throws InterruptedException.
Thread.sleep(), Object.wait(), join().
22. Best practice for "DO Nothing" Strategy for InterruptedException.
try { while (true) { Thread.sleep(2000) ; } } catch ( InterruptedException swallowedTheException ) { /* BAD PRACTICE */ } Instead re-interrupt the thread by calling interrupt() method. Because when the sleep() blocking method sniffs an interruption and throws InterruptedException, it clears the i...
23. Thread.sleep method()
This static method causes the current thread to suspend its execution for a specified period of time so that processor be available for the other threads of the application or yielding for other thread to complete. sleep() method is overloaded and there are two versions. public static void sleep(...
24. How do you interrupt an thread that does not call any method that throws InterruptedException?
We may add check as explained below. if (Thread.interrupted()) { return; }
25. join() method.
An Instance method of a thread object. It pauses the current thread execution in which the statement is called until the thread object on which join method is invoked complete its execution. Consider an example Without using join(). package com.tutorials.threading; public class ThreadJoinExample ...
26. Interrupts
indicates that the object has to stop doing what it does by calling interrupt() on the thread object. When it receives an interrupt, it returns from the run() method . package com.tutorials.threading; public class HandleInterruptedException { public static void main(String[] args) { String change...
27. is join() a overloaded method?
Yes. public final void join() pause for the invoking thread object to complete. public final synchronized void join (long milliSeconds) pause for the invoking thread object to complete or resume after the specified milliseconds. public final synchronized void join (long milliSeconds, int nano) pa...
28. An example for join(long milliseconds).
package com.tutorials.threading; public class WaitForMSToJoinExample implements Runnable { public static void main(String[] args) throws InterruptedException { WaitForMSToJoinExample myObj = new WaitForMSToJoinExample(); Thread MyThreadObj = new Thread(myObj, "Child Thread" ); MyThreadObj.start()...
29. How do you interrupt an thread that does not call any method that throws InterruptedException?
We may add check as explained below. if (Thread.interrupted()) { throw new InterruptedException(); }
30. Explain the interrupt mechanism.
The internal flag "interrupt status" tracks the status. Thread.interrupt() sets this flag and this flag is reset when Thread.interrupted (static) method is invoked to check the interruption status. The non-static isInterrupted method, which queries the interrup status of another, does not change ...
31. Can run() method throw exception?
No.
32. Difference between sleep and wait method in Java.
Although both methods pause the execution of the currently running thread, sleep() is meant for suspending the execution for short pause as it does not release the lock, while wait() is a conditional wait and it releases lock which can be acquired by another thread to change the condition on whic...
33. Is ++ (increment) operator thread-safe in Java?
No. Neither increment operator (++) nor the decrement operaor (--) is thread safe. For example, the statement i++ is not atomic. It involves multiple instructions that includes reading the value of i variable, increment its value by 1 and store the new i value to the variable.
34. What is thread starvation?
When a thread is not granted CPU time because other threads were using it all, it is called starvation . The thread starves to death because other threads are using the CPU time instead of it.
35. Does pressing Control-C causes InterruptedException in Java?
No. Invoking the interrupt() method in a thread only triggers InterruptedException while that thread executing a method that throws InterruptedException.
36. What is livelock in multithreading?
A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. It is a recursive situation where two or more threads would keep repeating a particular code logic. The intended logic is typ...
37. Explain race condition in multithreading.
Race conditions occurs when 2 or more threads operate on same object without proper synchronization and the steps on the operation interleaves on other thread. An example of Race condition is incrementing a counter since increment is not an atomic operation and can be further divided into three s...
38. What causes starvation in threads?
Threads with high priority takes up all CPU time from threads with lower priority. Threads are blocked indefinitely waiting to enter a synchronized block. Threads waiting on an object by calling wait() and remain waiting indefinitely.
39. Difference between deadlock and livelock in Java multithreading.
A deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock. A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another however none progressing. Livelo...
40. What is Slipped Condition in multithreading?
Slipped conditions represents that from the time a thread has checked a certain condition until it acts upon it, the condition has been changed by another thread so that it is erroneous for the first thread to act.
41. What is Intrinsic Lock in Java multithreading?
Synchronization is internally controlled by an entity known as the intrinsic lock or monitor lock. Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state to one thread and preventing access to other threads and establishing happens-before r...
42. Explain Guarded Blocks in Java.
Guarded block is a mechanism of coordinating the execution of multiple threads in a multithreaded environment. Guarded block keeps checking for a particular condition to become true and only in that case the actual execution of the thread resumes. Guarded blocks are of 2 types, synchronized guard...
43. What is BLOCKED state of a thread?
A thread is said to be in BLOCKED state when it waits to acquire a object's monitor.
44. Different states of a Java thread.
A thread can be in one of the following states: NEW: A thread that has not yet started is in this state. RUNNABLE: A thread executing in the Java virtual machine is in this state. BLOCKED: A thread that is blocked waiting for a monitor lock is in this state. WAITING: A thread that is waiting inde...
45. Difference between thread state WAIT and BLOCKED.
A thread gets to wait state once it calls wait() on an Object. This is called Waiting State. Once a thread attains waiting state , it will continue to wait till some other thread notify() or notifyAll() on the object. Once this thread is notified, it will not be runnable. It might be that other t...
46. Difference between synchronizing a static method and a non static method in Java.
Synchronization in Java is basically an implementation of monitors. When synchronizing a non static method, the monitor belongs to the instance. When synchronizing on a static method, the monitor belongs to the class. A synchronized method acquires a monitor before it executes. For a class (stati...
47. What is reentrant synchronization in Java?
Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code block synchronized on the same monitor object. A thread cannot acqui...
48. What is Reentrant lock in Java?
java.util. concurrent.locks ReentrantLock is a concrete implementation of Lock interface provided in Java concurrency package introduced in Java 1.5. ReentrantLock is a mutual exclusive lock with extended feature like fairness, which can be used to provide lock to longest waiting thread. Reentran...
49. Can a thread hold more than one lock at the same time?
Yes. A thread can have more than one lock. synchronized (obj1) { synchronized (obj2) { //some code... } }
50. Difference between synchronized method and synchronized block in Java.
A synchronized method uses the method receiver as a lock, 'this' for non static methods and the enclosing class for static methods. Synchronized blocks uses the expression as a lock. A synchronized method locks on the object instance the method is contained in while a synchronized block can lock ...
51. What is Runnable in Java?
Runnable represents a task in Java which is executed by Thread. java.lang.Runnable is an interface that defines only one method called run(). When a Thread is started in Java by using Thread.start() method it calls and execute the run() method of Runnable task which was passed to Thread when crea...
52. Difference between start and run methods in Java Thread.
when a program calls start() method, a new thread will be created and code inside run() method is executed in newly created thread whereas if the program calls run() method directly no new Thread be created and code inside run() will execute on current Thread itself.
53. Define Critical section in Java multi-threading.
A critical section represents a section of code or a block that is executed by multiple threads at the same time and where the sequence of execution of the threads makes a difference in the result of the concurrent execution of the critical section.
54. Explain IllegalMonitorStateException in Java multi-threading.
This run-time exception is thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor. It is mandatory that a thread cannot call wait(), notify() or notifyAll() without holding the lo...
55. What is Spurious Wakeups in Java threads?
The thread on WAIT state on an object wakes up for no reason, it is neither notified, timed out nor interrupted.For some reasons it is possible for a thread to wake up even if notify() and notifyAll() has not been called. This behavior is known as spurious wakeups, Wakeups without any reason.
56. What is Daemon thread in Java?
Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task. A daemon thread is a thread that does not prevent the JVM from exiting when the Java program finishes but the thread is still running. An example for a daemon thread is the ga...
57. Difference between Daemon and Non Daemon thread in Java.
JVM doesn't wait for any daemon thread to finish the Java program before exiting while JVM waits for all the non-daemon thread to complete before exiting the Java program. When JVM terminates, it doesn't not invoke the daemon thread's finally block or unwind the stack. However it is not the case ...
58. Difference between a wait() and sleep() in Threads.
A wait can be "woken up" by another thread calling notify on the monitor which is being waited on whereas a sleep cannot. A wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not. You call wait on Object itself whereas you call sleep on Thread. While sl...
59. Difference between concurrency and parallelism.
Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. An application can be concurrent when multiple tasks are performed simultaneously with shared resources. An application is parallel when a single task is divided into multiple simple indep...
60. Explain wait(), notify() and notifyAll() methods in Java threading.
The Object class in Java has 3 final methods that allow threads to communicate about the locked status of a resource. wait() instructs the calling thread to release the lock and go to sleep until some other thread enters the same monitor and calls notify(). The wait() method releases the lock pri...
61. Can a thread wait on multiple objects in Java?
No. A thread cannot wait on more than one object at a time. The wait() and notify() methods are object specific and invoke on the object. The wait() method suspends the current thread of execution, and instructs the object to keep track of the suspended thread. The notify() method tells the objec...
62. What is mutex in Java?
Official Definition is as follows: Mutexes are typically used to serialize access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to th...
63. Explain semaphore in Java.
The Official Definition is as follows: A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore).
64. Difference between Mutex and Semaphore in Java.
Mutex is basically mutual exclusion. Only one thread can acquire the resource at once and others wait. Semaphore is used to control the number of threads executing. There will be fixed set of resources. When the semaphore count reaches 0 then no other threads are allowed to acquire the resource. ...
65. Difference between notify and interrupt in Java.
When a thread calls notify on some monitor, it wakes up a single thread that's waiting on that monitor, but which thread gets woken is decided by the scheduler. Unlike notify, interruption targets a specific thread and interruption does not require that the interrupted thread be waiting on a moni...
66. Difference between notify and notifyAll in Java.
The key difference between notify and notifyAll is that notify() will cause only one thread to wake up while notifyAll method will make all the wating thread to wake up. When a thread calls notify on some monitor, it wakes up a single thread that's waiting on that monitor, but which thread gets w...
67. When the lock is released after notify/notifyAll is called?
The monitor is released only after completing the remaining statements of the synchronized code even after the thread calls notify or notifyAll on the object.
68. Why do we use ReentrantLock over synchronized (this)?
A ReentrantLock is unstructured and flexible compared to the synchronized constructs. We don't need to use a block structure for locking and can even hold a lock across methods. private ReentrantLock lock; public void method1 () { ... lock.lock(); ... } public void method2 () { ... lock.unlock();...
69. Define Liveness in Java Thread.
A concurrent application's ability to execute in a timely manner is known as its liveness. The liveness problems include deadlock, starvation and livelock.
70. How threads communicate with each other?
Threads can communicate with each other by using wait(), notify() and notifyAll() methods.
71. Difference between synchronized and volatile keyword in Java.
Volatile keyword is used on the variables and not on method while synchronized keyword is applied on methods and blocks not on variables. Volatile does not acquire any lock on variable or object, but synchronized statement acquires lock on method or block in which it is used. Volatile does not ca...
72. Explain Thread Priority.
Every thread has a priority, usually threads with higher priority gets precedence in execution but it depends on Thread scheduler. We can specify the priority of thread but it doesn't guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int w...
73. What is Thread Scheduler?
Thread Scheduler is the service that allocates the CPU time to the available runnable threads. Once a thread is created and started, it?s execution rely on the implementation of Thread Scheduler. Thread scheduler is OS dependent.
74. Define time slicing.
Time Slicing is the process to split the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the longest waiting thread will gets priority.
75. Define context-switching in multi-threading.
Context Switching is the process of storing and restoring of CPU state so that the thread execution can be resumed from the same point at a later point of time. Context Switching is an essential feature for multitasking and for multi-threaded environment.
76. Which is preferred - Synchronized method or Synchronized block?
Synchronized block is preferred as it provides more granular control. It only locks the critical section of the code and that eliminates unnecessary object locking.
77. Why wait, notify and notifyAll are declared in Object class and not in Thread class?
Every Object is associated with a monitor, only one thread can hold the monitor at a time. Acquiring the object monitor allow thread to hold lock on object. These methods are not called on the thread as it does not have its own lock. As the monitor is with the object, wait is called on the object...
78. What is Thread Group in Java?
ThreadGroup is a class that provides information about a thread group. It helps to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. Ever since setUncaughtExceptionHandler (UncaughtExceptionHandler e) was added in Java 1.5, it serves the pu...
79. Explain setUncaughtExceptionHandler method of Java Thread class.
The java.lang.Thread. setUncaughtExceptionHandler() method sets the handler to be invoked when this thread abruptly terminates due to an uncaught exception. public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) This method does not return any thing. public class ExceptionHan...
80. What is Thread dump?
A thread dump is a snapshot of the state of all threads that are part of the process. The state of each thread is presented with a stack trace, which shows the contents of a thread's stack. Some of the threads belong to the Java application you are running, while others are JVM internal threads. ...
81. Explain about jstack tool.
The jstack command-line utility attaches to the specified process or core file and prints the stack traces of all threads that are attached to the virtual machine, including Java threads and VM internal threads, and optionally native stack frames. The utility also performs deadlock detection. A s...
82. How to debug and analyse Thread deadlock?
We may analyse any deadlock by getting the thread dump and verifying the stack trace of the active threads. we may looks for the threads that are BLOCKED, the resource it is waiting for, the thread that is currently holding the lock from the stack trace. Since JDK 1.5 there are some powerful meth...
83. Can we not override run method when we extend Thread class?
Yes. we can avoid overriding run method while extending Thread class. The start method will execute the default implementation which has no action.
84. Define Java thread pool.
Java Thread pool is a group of worker threads that are waiting for the tasks to be assigned and be reused again. Worker threads return to the thread pool after it completes its task. A group of fixed size threads are created in the thread pool. A thread from the thread pool is chosen and assigned...
85. Advantages of using threadpool.
Improves performance of multithreaded application as the thread pool eliminates the overhead of creating/recreating thread objects.
86. What are atomic classes in Java Concurrency API?
The java.util.concurrent. atomic package defines classes that support atomic operations on single variables. All classes have get and set methods to read and write similar to volatile variables. import java.util.concurrent.atomic.AtomicInteger ; public class AtomicCounter { private AtomicInteger ...
87. What is Lock interface in Java Concurrency API?
A lock is a thread synchronization mechanism like synchronized blocks that are sophisticated than Java's synchronized blocks. From Java 5 the package java.util.concurrent.locks contains several lock implementations. The advantages of using locks are, implements fairness. possible to try to acquir...
88. Define preemptive scheduling.
In preemptive scheduling, the thread with highest priority executes until it enters into the waiting or dead state.
89. What is the priority for Daemon threads?
Priority of daemon threads is always 1, the lowest priority. Thread scheduler schedules these threads only when CPU is idle.
90. Explain yield() method of a thread.
yield() method gives a notice to the thread scheduler that the current thread is willing to yield its current use of a processor. The thread scheduler is free to ignore this hint.
91. Can 2 threads call different synchronized instance methods of same Object?
No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
92. What is thread leak in Java?
Thread leak happens when an application does not release references to a thread object properly that prevents the thread from being garbage collected. Thread leak can cause performance issues and application slowness, when too many threads gets created and not garbage collected after it attains t...
93. What is CountDownLatch in Java?
CountDownLatch is a synchronizer type which allows one Thread to wait for one or more Threads before starts processing. A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. A CountDownLatch is initialized with a given ...
94. Applications of CountDownLatch in Java thread.
CountDownLatch works in latch principle, main thread will wait until gate is open. One thread waits for n number of threads specified while creating CountDownLatch in Java. Classical example of using CountDownLatch in Java is any server side core Java application which uses services architecture,...
95. Explain CyclicBarrier in Java thread.
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after th...
96. Difference between wait-notify and CountDownLatch.
CountDownLatch behavior could be achieved using low level constructs such as wait-notify, synchronized. CountDownLatch is built using such constructs only.
97. How do you create an immutable class in Java?
An object is considered immutable if its state cannot change after it is constructed. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. The below are the rules...
98. What is the purpose of the class java.lang.ThreadLocal?
You can find the ThreadLocal questions here .
99. Explain volatile keyword in Java.
Find the volatile related questions here .
100. Explain fork/join framework in Java thread.
The fork/join framework is an implementation of the ExecutorService interface that helps you deal with multiple processors. It is designed for tasks that can be broken into smaller subtasks recursively. The goal is to use all the available processing power to enhance the performance of your appli...
101. Explain Fork-Join framework API.
The core of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTask processes.
102. Explain Exchanger in Java thread.
Exchanger is a synchronization point at which threads can pair and swap elements between the pair. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner's object on return. An Exchanger may be viewed as a bidirectional form of a ...
103. Difference between ReadLock and WriteLock in Java ReentrantReadWriteLock.
When a thread acquires a WriteLock, no other thread can acquire the ReadLock nor the WriteLock of the same instance of ReentrantReadWriteLock, unless that thread releases the lock. However, multiple threads can acquire the ReadLock at the same time.
104. General practice for releasing lock while using Lock implementation in Java.
When using any of the Lock implementation the lock is usually released in finally block. This ensures that if there is exception in method body, lock is released. public void method () { reentrantLock.lock() ; try { //perform task } finally { reentrantLock.unlock() ; } }
105. Advantages of using Lock implementations in Java threading.
Non-blocking or optimistic attempt to acquire a lock using tryLock , attempt to acquire the lock that can be interrupted using lockInterruptibly, attempt to acquire a lock that can timeout using tryLock(long time, TimeUnit unit), guaranteed ordering, and deadlock detection.
106. Difference between Runnable and Callable interfaces in Java.
The Callable interface is similar to Runnable,both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception unlike Callable which returns a result and throw exceptions.
107. What is the Threads interrupt flag?
The interrupt flag or interrupt status, is an internal Thread flag that is set when the thread is interrupted. To set it, simply call thread.interrupt() on the thread object. If a thread is currently inside one of the methods that throw InterruptedException (wait, join, sleep), then this method i...
108. What is FutureTask Class?
FutureTask implements Future interface and provides asynchronous processing. It contains the methods to start and cancel a task and also methods that can return the state of the FutureTask as whether its completed or cancelled. We need a callable object to create a future task and then we can us...
109. What are some common problems you face in multi-thread programming?
Memory-interference, race conditions, deadlock, livelock, and starvation are example of problems we encounter in multi-threading and concurrent programming.
110. Limitations of Future.
You cannot perform any further action/callback on a Futures result without blocking since Future does not notify when completed. It provides get() method that blocks until the result is ready. Multiple Future cannot be chained together, for example, the result of one Future cannot be sent to oth...
111. What is the enhanced version of Future (or) alternative to Future?
CompletableFuture achieves all the limitations in Future. CompletableFuture implements Future and CompletionStage interfaces and provides a huge set of convenience methods for creating, chaining and combining multiple Futures. It also has a very comprehensive exception handling support .
112. Difference between green and native threads.
Green threads refers to a model in which the Java virtual machine itself creates, manages, and context switches all Java threads within one operating system process. No operating system threads library is used. Green threads are in past, JVMs work only with native threads since 1.3. Native thread...