Java wait()/join(): Why does this not deadlock? - java

Given the following Java code:
public class Test {
static private class MyThread extends Thread {
private boolean mustShutdown = false;
#Override
public synchronized void run() {
// loop and do nothing, just wait until we must shut down
while (!mustShutdown) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception on wait()");
}
}
}
public synchronized void shutdown() throws InterruptedException {
// set flag for termination, notify the thread and wait for it to die
mustShutdown = true;
notify();
join(); // lock still being held here, due to 'synchronized'
}
}
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
try {
Thread.sleep(1000);
mt.shutdown();
} catch (InterruptedException e) {
System.out.println("Exception in main()");
}
}
}
Running this will wait for one second and then properly exit. But that is unexpected to me, I expect a dead-lock to happen here.
My reasoning is as follows: The newly created MyThread will execute run(), which is declared as 'synchronized', so that it may call wait() and safely read 'mustShutdown'; during that wait() call, the lock is released and re-acquired upon returning, as described in the documentation of wait(). After one second, the main thread executes shutdown(), which is again synchronized as to not access mustShutdown at the same time as it's being read by the other thread. It then wakes up the other thread via notify() and the waits for its completion via join().
But in my opinion, there's no way that the other thread can ever return from wait(), since it needs to re-acquire the lock on the thread object before returning. It cannot do so because shutdown() still holds the lock while inside join(). Why does it still work and exit properly?

join() method internally calls wait() which will result in releasing of the lock(of Thread object).
See the code of join() below:
public final synchronized void join(long millis)
throws InterruptedException {
....
if (millis == 0) {
while (isAlive()) {
wait(0); //ends up releasing lock
}
}
....
}
Reason why your code sees this and not seen in general:: The reason why your code see this and not is not observed in general, is because the join() method waits() on Thread object itself and consequently relinquishes lock on the Thread object itself and as your run() method also synchronizes on the same Thread object, you see this otherwise unexpected scenario.

The implementation of Thread.join uses wait, which lets go of its lock, which is why it doesn't prevent the other thread from acquiring the lock.
Here is a step-by-step description of what happens in this example:
Starting the MyThread thread in the main method results in a new thread executing the MyThread run method. The main Thread sleeps for a whole second, giving the new Thread plenty of time to start up and acquire the lock on the MyThread object.
The new thread can then enter the wait method and release its lock. At this point the new thread goes dormant, it won't try to acquire the lock again until it is woken up. The thread does not return from the wait method yet.
At this point the main thread wakes up from sleeping and calls shutdown on the MyThread object. It has no problem acquiring the lock because the new thread released it once it started waiting. The main thread calls notify now. Entering the join method, the main thread checks that the new thread is still alive, then waits, releasing the lock.
The notification happens once the main thread releases the lock. Since the new thread was in the wait set for the lock at the time the main thread called notify, the new thread receives the notification and wakes up. It can acquire the lock, leave the wait method, and finish executing the run method, finally releasing the lock.
The termination of the new thread causes all threads waiting on its lock to receive a notification. This wakes up the main thread, it can acquire the lock and check that the new thread is dead, then it will exit the join method and finish executing.
/**
* Waits at most <code>millis</code> milliseconds for this thread to
* die. A timeout of <code>0</code> means to wait forever.
*
* #param millis the time to wait in milliseconds.
* #exception InterruptedException if any thread has interrupted
* the current thread. The <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
*/
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}

To complement the other answers: I see no mention of join() releasing any locks in the API-documentation, so this behavior is actually implementation-specific.
Learn from this:
don't subclass Thread, instead use a Runnable implementation passed to your thread object.
don't synchronize/wait/notify on objects you don't "own", e.g. where you don't know who else might synchronize/wait/notify on it.

Related

Behavior of wait() and notifyAll() in Java?

Please note that this is not the actual scenario. I created a sample scenario based on my actual implementation, to make it easy to review. I am also already getting the expected output too. However, I need to clarify some concepts regarding the wait() and notifyAll() methods in Java. (In here both these threads will starts there run method at once in the main thread.) So according to my knowledge, since thread B is sleeping, because you can see at the initial stage reamingCount is 400.
So thread B will calls its MUTEX.wait() and continue its sleep until some other thread invokes a notify() or notifyAll(), then after the remainingCount decrements to 0, thread A will call MUTEX.notifyAll(); to awake the thread B and MUTEX.wait() to release its already granted lock, and go to sleep until thread B notifies it.
When I call MUTEX.notifyAll() through thread A, won't thread B wake up and continue its task before thread A calls MUTEX.wait()?
I mean, you can see when thread A calls the MUTEX.notifyAll(), thread B will awake and check again if the condition in the while loop is true or false. So, since the remainingCount is equal to 0, thread B will exit the while loop and continue its task before thread A calls wait(). Won't this scenario break the principle of wait()? According to my knowledge thread B can only continue its execution when thread A calls wait().
public class A implements Runnable{
public static volatile remainingCount =400;
private final Object MUTEX;//Both class A and B holds the same object mutex
private void methodA(){
synchronized(MUTEX){
while(remainingCount == 0){
MUTEX.notifyAll();
MUTEX.wait();
}
//Perform it's usual task.In here remaining count will decrement during the process.
}
#Override
public void run() {
while(true){
methodA();
}
}
}
}
public class B implements Runnable{
private final Object MUTEX;//Both class A and B holds the same object mutex
private void methodB(){
synchronized(MUTEX){
while (A.remainingCount != 0) {
try {
MUTEX.wait();
} catch (InterruptedException ex) {
Logger.getLogger(InkServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
//incrementing the A.remainingCount
MUTEX.notifyAll();
}
#Override
public void run() {
while(true){
methodB();
}
}
}
When a thread holding a lock calls wait() on the locked object, the thread is added to the object's wait set and the lock is released.
When a thread holding a lock calls notify(), and the wait set is not empty, a thread in the wait set is selected and removed. Likewise, calling notifyAll() removes all threads from the wait set.
Note: threads can also be removed from the wait set by a call to thread.interrupt().
When a thread is removed from the wait set and begins to run, the first step is to reacquire the lock. This happens before the return from wait().
This will not happen until the thread that called notify() or notifyAll() releases the lock by either calling wait() or exiting the synchronized block.
So, while your thread B has been enabled to run, it won't actually return from wait() until thread A releases the lock by calling MUTEX.wait(). Likewise, thread A is enabled to run when B calls MUTEX.notifyAll(), but doesn't return from wait() until thread B exits the synchronized(MUTEX) block.

java thread: Thread.interrupt() not working

I need to kill a thread that is not created in my code. In other words, the thread object is created by api (Eclipse JFace). Here is my code
ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
try {
IRunnableWithProgress rp = new IRunnableWithProgress(){
#Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
Thread.sleep(3000);
Thread t = Thread.currentThread();
t.getThreadGroup().list();
t.interrupt();
}
};
dialog.run(true, true, rp);
}
catch (Exception e) {
e.printStackTrace();
}
Thread.currentThread() returns a thread with the name "ModalContext". Line t.getThreadGroup().list() returns the following data:
...
Thread[qtp1821431-38,5,main]
Thread[qtp1821431-39,5,main]
Thread[qtp1821431-40,5,main]
Thread[qtp1821431-42 Acceptor0 SelectChannelConnector#0.0.0.0:18080,5,main]
Thread[DestroyJavaVM,5,main]
Thread[ModalContext,5,main]
Variables "dialog" and "rp" do not have reference to their runnable object. And they don't have any method to close or cancel. So I want to kill that thread "ModalContext" directly. Calling t.interrupt() does not work. Thread MoadlContext continues to run. How can I kill the thread? Thanks
The interrupt method doesn't kill the thread. It sets the "interrupted" status on the Thread, and if it's sleeping or waiting on I/O, then that method that it's calling will throw an InterruptedException.
However, you call interrupt on the current thread after sleep finishes, so this will do nothing but set the "interrupted" status.
You can do one of the following:
Have another Thread call interrupt on that Thread. In run(), let the method complete if an InterruptedException is caught or if interrupted() returns true.
Declare a volatile boolean variable (say, isRunning) that is initialized to true in the created thread. That thread will let the run() method complete if it's false. Have another Thread set it to false at the appropriate time.
t.interrupt() does not actually interrupt the thread immediately it only update interrupt status of thread. If your thread contains method which poll the interrupt status (i.e. sleep )only then the thread will be interrupted otherwise the thread simply complete the execution and interrupt status will be ignored.
Consider following example,
class RunMe implements Runnable {
#Override
public void run() {
System.out.println("Executing :"+Thread.currentThread().getName());
for(int i = 1; i <= 5; i++) {
System.out.println("Inside loop for i = " +i);
}
System.out.println("Execution completed");
}
}
public class Interrupted {
public static void main(String[] args) {
RunMe runMe = new RunMe();
Thread t1 = new Thread(runMe);
t1.start();
t1.interrupt();//interrupt ignored
System.out.println("Interrupt method called to interrupt t1");
}
}
OUTPUT
Interrupt method called to interrupt t1
Executing :Thread-0
Inside loop for i = 1
Inside loop for i = 2
Inside loop for i = 3
Inside loop for i = 4
Inside loop for i = 5
Execution completed
Now just add Thread.sleep(200); in run and you will see the InterruptedException.

Why is that sleeping inside a thread causes problems with `notify`?

Driver.java
public class Driver {
static Object obj = new Object();
public static void main(String [] args) throws InterruptedException
{
Thread thr = new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Thread 1: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 1: Completed processing.");
System.out.println("Thread 1: Notifying other waiting threads.");
obj.notify();
}
}
});
Thread thr2 = new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Thread 2: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 2: Completed processing.");
System.out.println("Thread 2: Notifying other waiting threads.");
obj.notify();
}
}
});
thr.start();
thr2.start();
System.out.println("Main Thread: All processing units busy.");
// Thread.sleep(2000); // Enable this and disable the other Thread.sleep(...) and NOW we are good. But again, 'why?' is the question.
synchronized(obj){
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
System.out.println("Main Thread: Found ONLY 1 available slot.");
obj.notify();
obj.wait(); // JVM should catch this as the last request so it has the least priority.
System.out.println("Main Thread: Finished and exiting...");
}
}
}
The code above will not notify the Threads because of the following line:
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
Please take a look at this line in context with the whole class. I am having hard time pinpointing to the reason why this simple proof-of-concept would fail if that line is placed inside ther synchronized block in the Main Thread.
Thank you
The problem is not the sleep but rather that the main thread almost always acquires the lock before one (and occasionally both) of the created threads does. If you print just inside the synchronized blocks it's much more clear what is going on:
synchronized(obj) {
System.out.println("this thread acquired the lock");
You'll see the output is almost always Thread #1, then the main thread, and finally Thread #2 after Thread #1 completes (but main has already returned).
If you run it enough times sometimes both child threads do acquire the lock first and it completes.
The reason moving the sleep to outside the synchronized block in the main thread works is it allows both child threads to reach their respective wait statements.
Read the doc.
Wakes up a single thread that is waiting on this object's
monitor.
If it is sleeping then it is not waiting.
There is other related problem, it is not possible to reach the notify line while the other thread is in the sleep as it keeps the monitor (lock) and the other thread can't run inside the synchronized block. This is always that way as both wait and notify must be run inside related syncrhonized blocks (against the same monitor).
sleep holds the lock, but wait doesn't. so when your main thread is sleeping, both thr and thr2 can't get the lock until main thread notifies them. At that moment, they start to wait and can't receive any notify()
The problem is that sleep does not release the monitor, that is: while the main thread is sleeping, all the other threads cannot enter the synchronized block, so they are basically sleeping with the main thread.
The moment the main thread wakes up, it does notify, but since no one yet entered the wait() position, no one is listening. Then the main thread waits and therefore releases the monitor, so now all threads can proceed to the wait() state, but no one is left to wake them up. -> Deadlock

why Interrupted exception thrown here...reason?

public class TwoThreads {
private static Object resource = new Object();
private static void delay(long n) {
try
{
Thread.sleep(n);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.print("StartMain ");
new Thread1().start();
delay(1000); //dealay 1
Thread t2 = new Thread2();
t2.start();
delay(1000); // delay 2
t2.interrupt(); //here its throwing exception
delay(1000); //delay 3
System.out.print("EndMain ");
}
static class Thread1 extends Thread {
public void run() {
synchronized (resource) {
System.out.print("Startl ");
delay(6000);
System.out.print("End1 ");
}
}
}
static class Thread2 extends Thread {
public void run() {
synchronized (resource) {
System.out.print("Start2 ");
delay(2000);
System.out.print("End2 ");
}
}
}
}
I just got confused here why t2.interrupt() is not throwing exception when t2 is waiting to acquire lock on resource object and interrupt() method might throw security exception then why compiler still allowing us to execute it without putting it into try catch block.
A synchronized block doesn't throw an InterruptedException and interrupting a thread blocking while attempting to acquire a monitor this way doesn't do anything.
If you want this functionality you need to use a Lock which has lockInterruptibly(), though this is not often used.
Acquires the lock unless the current thread is interrupted. Acquires
the lock if it is not held by another thread and returns immediately,
setting the lock hold count to one.
If the current thread already holds this lock then the hold count is
incremented by one and the method returns immediately.
If the lock is held by another thread then the current thread becomes
disabled for thread scheduling purposes and lies dormant until one of
two things happens:
The lock is acquired by the current thread; or Some other thread
interrupts the current thread. If the lock is acquired by the current
thread then the lock hold count is set to one.
If the current thread:
has its interrupted status set on entry to this method; or is
interrupted while acquiring the lock, then InterruptedException is
thrown and the current thread's interrupted status is cleared.
From Thread#interrupt():
If none of the previous conditions hold then this thread's interrupt status will be set.
If you checked t2.interrupted(), you'd see a true result, but the thread is blocking on entering the synchronized block, which doesn't trigger an InterruptedException.
A call to interrupt() may throw a SecurityException if the application's environment has set up restrictions on which threads can interact with others, but this doesn't apply in your simple example.
The question is unclear but I guess I understood it correct so I am attempting to answer.
syncrhonized blocks are NOT responsive to interrupts.
For that you can use explicit locks Lock, which has a method lockInterruptibly() which is responsive to interrupts.
lockInterruptibly() in Lock Interface
java.lang.Thread.interrupt() means Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
you have called sleep() on t2. that is the reason of getting interruptedException.

Why was task1 thread not interrupted

Assume the below code is executed with a debugger so that we can predict the order of execution.
t1 -- Here task1 starts working on some long task.
t2 --- task2 gets blocked # Syncronized statement because task1 is holding lock.
t3 -- task2 is interrupted but its missed because task2 is using intrinsic locks and hence cannot be interrupted # synchronized. (Renenterant.lockInterruptible() would have thrown InterruptedExecption).
t4 --- task1 is interrupted. However despite of doing the complex task in try catch block, InterruptedExecption was never thrown. Why is that ?
Code:
public class TestInteruptibility {
public static Object lock = new Object();
public static boolean spin = true;
public static void main(String[] args) {
Thread task1 = new Thread(new Task(), "Task1");
Thread task2 = new Thread(new Task(), "Task2");
Thread notifier1 = new Thread(new Notifier(), "Notifier1");
task1.start();
task2.start();
task2.interrupt();
task1.interrupt();
notifier1.start();
}
}
class Task implements Runnable {
public void run() {
synchronized (TestInteruptibility.lock) {
System.out.println("Performing Long Task");
try {
while (TestInteruptibility.spin) {
}
System.out.println("Finsihed Performing Long Task");
TestInteruptibility.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("I got interrupted while i was waiting # wait()");
}
System.out.println("Ending Task");
}
}
}
class Notifier implements Runnable {
public void run() {
synchronized (TestInteruptibility.lock) {
System.out.println("Performing notification");
TestInteruptibility.lock.notify();
System.out.println("Ending notification");
}
}
}
Basically, what interrupt() does is to set a flag in the Thread object. And you need to check it with isInterrupted(). Then you can handle this interrupt signal. It won't throw an InterruptedException in this situation.
Besides, it can cause some methods, for example, Thread.sleep(), Object.wait(), to return immediately and throw an InterruptedException. And you can get and InterruptedException in this situation.
From Java Concurrency in Practice, 7.1.1. Interruption:
A good way to think about interruption is that it does not actually interrupt a running thread; it just requests that the thread interrupt itself at the next convenient opportunity. (These opportunities are called cancellation points.) Some methods, such as wait, sleep, and join, take such requests seriously, throwing an exception when they receive an interrupt request or encounter an already set interrupt status upon entry. Well behaved methods may totally ignore such requests so long as they leave the interruption request in place so that calling code can do something with it. Poorly behaved methods swallow the interrupt request, thus denying code further up the call stack the opportunity to act on it.
In your above code, you are not waiting/sleeping. So you have to check isInterrupted() and handle interrupt signal yourself in the while loop.
while (TestInteruptibility.spin) {
if (Thread.currentThread().isInterrupted()) {
break;
}
}
References:
why interrupt() not work as expected and how does it work
What does java.lang.Thread.interrupt() do?
You have a busy while loop, that holds the lock (and never ends, unless you change spin's value somewhere). I suppose that task1 is still in the loop, therefore it doesn't notice the interruption. Task2 can't acquire the lock, so it blocks.
The way Task is implemented, it can only be interrupted in during the wait command, which comes after the loop.
BTW: if you are using the spin data member in different threads, then it should probably be declared as volatile. For similar thread safety reasons, lock should be declared as final.
When you call method interrupt() the result depends on the this thread is doing currently. If it is blocked on some interruptable method such as Object.wait(), then it will be interrupted immediately, which means that InterruptedException will be throw inside the thread. If thread is not blocked, but is doing some calculations, or it is block on some non-interruptable method such as InputStream.read() then InterruptedException is not thrown, but interrupted flag is set on thread instead. This flag will cause InterruptedException next time thread will call some interruptable method, but not now.
In your case threads task1 and task2 are spinning in infinite empty loops and thus are not blocked on any interruptable methods, so when you call interrupt() on then, no InterruptedException is thrown inside that threads, but interrupted flag is just set. You probably should change your task code to look like this:
while (TestInteruptibility.spin && !Thread.interrupted ()) {
}
then you will exit from the loop as long as somebody will call interrupt on task thread.

Categories