Java Concurrency Questions.
Threading Interview Questions:-
- Why we need multi-threaded applications?
Now a day most of servers are coming with multiple processors. To take benefit of these multi core processing capabilities, we need to run application with multiple processes concurrently. In Java, Thread is one of the way to create these light weight process, which can execute at same time and perform tasks.
- What is synchronization ?
Synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
- Different way of creating thread?
The thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.
a) public class MyThread extends Thread
b) public class MyThread implements Runnable
- What is the difference between Thread.start() & Thread.run() method?
Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread. In this sequence the thread changes state.
- Why do we need run() & start() methods?
We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called.
Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.
- What is ThreadLocal class?
- A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
- ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
- In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
- Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
Good article on ThreadLocal: http://www-128.ibm.com/developerworks/java/library/j-threads3.html
Good example : http://javaboutique.internet.com/tutorials/localdata/
Multithreading in Swing: http://java.sun.com/developer/JDCTechTips/2003/tt1208.html
Refer API Docs: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html
- When InvalidMonitorStateException is thrown? Why?
This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll())
wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
- What is the difference between sleep(), suspend() and wait() ?
Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the
sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.
object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original,
waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
- What happens when I make a static method as synchronized?
Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.
- Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?
Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized.
Below is the example which demonstrates this, The Common class has two methods
synchronizedMethod1() and method1()
MyThread class is calling both the methods in separate threads,
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.
See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods.
13. What is Starvation? and What is a Livelock?
Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.
- When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
- When all the threads in a program are stuck in infinite loops.
Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU.
In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.
14. How to make sure Thread 1 , 2, 3 can run in sequence?
We can use join() to run the thread in sequence.
16. Why Java locks \ object monitors are re-entrant?
The Java runtime system allows a thread to re-acquire a monitor that it already holds because Java monitors are re-entrant. Re-entrant monitors are important because it eliminates the possibility of a thread deadlocking on a monitor that it already holds.
Read Java Concurrency for latest updates to create multithreaded applications