How to send interrupt signal to a thread from other thread - java

Suppose I have two threads using instance of same class, which is acting as monitor. For example Thread1 and Thread2 using same instance of class ABC 'o'.
Now there is synchronized method doProcess() in class ABC which is being called by both threads. I have some condition in doProcess(), due to which first thread is in wait() state. Now when second thread went inside doProcess(), there is condition which tells it to terminate the whole processing.
One solution is to notify first thread and update some flag to tell it that don't block again and complete.
What I was thinking, can I send any signal from my monitor object 'o' (just like notify and notifyAll), to all waiting threads to interrupt and terminate?
EDITED First Solution:
sync doProcess()
{
while( you are thread1 and !flag )
{
wait(); //line 3
}
if( you are thread2)
{
flag = true;
notifyAll(); //can i send send any interrupt signal to terminate all threads in line 3 itself;
}
}

Yes. The method is .interrupt()
This will throw and InterruptedException in the receiving thread, which should be handled in the run() method.
You'll still need to set the flag on the running thread, as the InterruptedException will not happen if the thread isn't blocking.

Related

Running wait() on a Thread instance from within main() in Java

I am playing around with the timed version of wait() in java.lang.Object and have observed that it acts differently in two different scenarios.
Scenario1: Using the default definition of run() in Thread
public static void main (String[] args) throws InterruptedException {
Thread t = new Thread();
t.start();
System.out.print("X");
synchronized(t) { t.wait(10000);}
System.out.print("Y");
}
Questions on scenario1: I am experiencing a delay between X and Y. Is this because I am calling wait() from main (even though, on t) and therefore the call stack of the main thread is being used, rather than that of the second thread?
Scenario2: Subclassing Thread on-the-fly to override run() in order to print something.
public static void main (String[] args) throws InterruptedException {
Thread t = new Thread() {public void run()
{System.out.print("I am the second thread.");}};
t.start();
System.out.print("X");
synchronized(t) { t.wait(10000);}
System.out.print("Y");
}
Questions on scenario2: I am NOT experiencing any delay at all! What has changed just because I have overridden run()? Now, each time I run the program it immediately prints "XI am the second thread.Y" without any delay, whatsoever! Where has the effect of wait() gone?
The explanation about how the thread finishing sends a notifyAll is relevant and correct, +1 from me. I'll try to add some information about why this is relevant.
When you call
synchronized(t) { t.wait(10000);}
in the main thread, it is the main thread that does the waiting. t is the monitor that the main thread is waiting on. Your expectation that this should make your t thread go dormant is mistaken.
The monitor here (the shared object being locked on, which happens to be t) is used to communicate between the different threads, a thread calls notifyAll on the monitor and the other threads waiting on the monitor receive the notification. You can think of the monitor as a shared communication point.
In your first example, the thread t starts and finishes immediately (because it doesn't have anything to do). The thread finishes and sends its notification before the main thread starts waiting, so you see a delay until the wait times out.
In the second example, the thread t has something to print, there's a race condition between it and the main thread. It's a free-for-all, what happens first depends on accidents of timing. What you're seeing is that the thread t now has to print a line to the console, so it manages to keep busy long enough that it's still alive at the time the main thread starts to wait, allowing the main thread to receive the notification when t finishes, causing the main thread to cut its wait short.
You have actually run into exactly why you should NEVER call wait or notify(All) on Thread (see the JavaDocs for Thread). Internally, Thread uses wait and notifyAll to implement Thread.join(), so what's happening in the second case is you thread enters wait, but then the other thread dies and calls notifyAll(), which wakes up your main thread.
Use Thread.sleep if you just want to wait for an elapsed time, use Thread.join if you actually want to wait for the thread’s termination. Also, read the javadocs in Object for proper usage of wait, notify, and notifyAll.
javaDoc:
public final void join(long millis)
throws InterruptedException
Waits at most millis milliseconds for this thread to die. A timeout of
0 means to wait forever. This implementation uses a loop of this.wait
calls conditioned on this.isAlive. As a thread terminates the
this.notifyAll method is invoked. It is recommended that applications
not use wait, notify, or notifyAll on Thread instances.

Does a thread need to be in a RUNNABLE state before it can be interrupted?

Is it necessary for a thread in java to be in ready state before it gets interrupted by interrupt method?
I tried to check this by typing the above given code below.
class MyThread extends Thread
{
public void run() {
try
{
for(int i =0;i<10;i++) {
System.out.println("I am lazy thread");
Thread.sleep(2000);
}
}
catch(InterruptedException e) {
System.out.println("I got interrupted");
}
}
}
public class SleepAndInterruptDemonstrationByDurga {
public static void main(String[] args) {
MyThread t= new MyThread();
t.start();
t.interrupt();
System.out.println("End of main thread");
}
}
The output what I got was always was the below one even after trying many times
End of main thread
I am lazy thread
I got interrupted
Why can't the output be
I am lazy thread
I got interrupted
End of main thread
as according to the code it can be seen that the interrupt method is called first by the main thread. Ultimately I want to ask that are there any situations possible when at first the interrupt call is executed before the the thread got started?
What happens here is
1) the thread you start needs time to get ready to run, so “end of main thread” is probably going to print first, though that’s not guaranteed.
2) the interrupt flag is set before the new thread is done starting, but nothing checks the status of that flag until the thread sleeps. When you call interrupt on a thread that only sets the flag, the thread doesn’t do anything to respond unless you put in calls to things like sleep or isInterrupted. So “I am lazy Thread” will show up before “I got interrupted”.
Interruption is voluntary and requires the cooperation of the interrupted thread. The thread can’t act on the interrupt flag status until it is running, because some code has to check the flag and act on it.
Is it necessary for a thread in java to be in ready state before it
gets interrupted by interrupt method?
The interrupt method doesn't really interrupt the thread. It only sets the interrupted status of the thread on which it is called. That said, if you reverse the call to the interrupt method and the start method, you will notice that the Thread doesn't get interrupted.
MyThread t = new MyThread();
t.interrupt();
t.start();
This should confirm that for the Thread.interrupt method to have an effect on a Thread, the minimum requirement would be that start was called on the Thread before the interrupt method.
Note There is no thread state called the ready state. What you are referring to is the RUNNABLE state which indicates that start was called on the Thread
If you want the main thread to wait for the other thread to finish what it has to do you should do t.join().
It is possible that the line System.out.println("End of main thread"); was executed before the threads start. On my computer the program may print End of main thread first, second or last.
As for your question, Java thread don't have a state called "ready" nor "interrupted" (see documentation). Thread.interrupt() just causes a thread to change its state to "TERMINATE".
Also see here:
Interrupting a thread that is not alive need not have any effect.

How to use wait and notify

I am creating a java application in which I am using three threads to perform three operations on a text file simultaneously.I have a toggle button in my application when I click start i am calling a method call() in which i am creating and starting all these threads and when i click stop i am calling a new method stopcall() in which i write a code to stop all these thread.
public void stopcall() throws Exception {
System.out.println("hello stop call");
synchronized(t) {
t.wait();
}
synchronized(t1) {
t1.wait();
}
synchronized(t2) {
t2.wait();
}
}
But stopcall() method is not working properly whenever i am calling this method my application hanged.I would be grateful if somebody help me and tell me how to use wait and notify in my application
Your application hangs because you are waiting for a locked object.
wait() method hangs the thread until another thread uses notify() on that object.
You have to synchronize the method that accessing the shared object (the file in this case) to enable safe threading. here is an example using a boolean flag to indicate if the resource is currently in use or not.
if in use, the next thread will invoke wait() and will wait for a notification.
meantime when the 'currently using' thread will finish the synchronized block - it will invoke notifyAll() to alert all the waiting threads that the resource is free.
public class TestSync {
private boolean fileInUse = false;
public synchronized void syncWriting() {
// blocks until a the file is free. if not - the thread will 'wait'.
// when notified : will do the while-loop again
while (true) {
if (!fileInUse){
System.out.println("using the free file");
fileInUse = true;
//
// code to write and close the file
//
notifyAll();
return;
}
try {
// wait if file in use. after being notified :
wait();
} catch (InterruptedException e) {e.getMessage();}
}
}
The wait()/notify()/notifyAll() methods are fairly easy to understand.
foo.wait() releases the lock on foo, and then it sleeps until foo is notified, and then in reacquires the lock before it returns.
foo.notifyAll() wakes up all threads that are sleeping in foo.wait() calls. If no threads are sleeping at the moment when it is called, then it does not do anything at all.
foo.notify() is the same as foo.notifyAll() except, it only picks one sleeping thread (if any) and wakes it.
The trick to using wait() and notify() is, suppose that you expect some thread A to wake up thread B with a foo.notify(). How do you guarantee that thread B will already be sleeping in a foo.wait() call before thread A calls foo.notify()?
Remember: If the notify happens first, then it will be "lost". That is, the notify will do nothing, and the wait will never return.
That brings us to the reason why foo.wait() and foo.notify() are only allowed to be called from inside a synchronized(foo) block. You are supposed to use the synchronization, and some shared variable to prevent thread A from wait()ing for a notification that already has happened.

Awake thread from sleep

I am creating an program and working with threads in details for the first time and stuck into an situation .Please help me in that.
I am having a thread which is in wait state.Now at some instance I want to kill or to awake thread and resume from another class .For this I am saving object of thread .I don't know how to do this .I tried to notify thread but got exception.Here is my code:
Class one:
Thread t= new Thread(new Runnable() {
#Override
public void run() {
try{
Thread.sleep(VariableClass.THREAD_WAIT_SECONDS);
if(message !=null)
message_status = message.getStatus();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
//do other stuff and save the thread object
VariableClass.threads.remove(message.getUniqueId());
}
});
t.start();
VariableClass.threads.put(pojo.getUniqueId(),t);
Class two:
Thread t =VariableClass.threads.get(tempId);
t.notify();
I just want to resume or kill thread.
If your thread t is sleeping, calling t.interrupt() will cause an InterruptedException to be thrown from the line calling Thread#sleep. It will get caught in your catch block and your thread will proceed from there to do its cleanup and exit.
If there was an issue where your thread was not sleeping or waiting but still wanted to be aware of whether it was interrupted, the code in your Runnable could check the interrupted flag on the current thread. Remember that the interrupted flag gets reset once an InterruptedException is thrown.
Wait and notify are for threads that are synchronizing on a monitor, that's not applicable to your example. Threads wait on a monitor and receive notifications, but the notifications are not made to a specific thread; for Object#notify, some thread waiting on that monitor gets chosen but the thread calling notify has no control over which one is picked.
Here's an example of using interrupt to wake a thread from sleeping.
Your thread is sleeping for the specified amount of time. Call interrupt on it, if you just want to "kill it" and you don't care too much what will happen with it later. You cannot simply "awake it" from another thread, if it's sleeping it has to sleep as much as it has been told to. Calling notify has nothing to do with this situation (there's no prior wait call). Even if did, you're calling it incorrectly.
You do not use notify in this case. I suggest reading the JavaDoc on #wait/#notify/#notifyAll
You use #notify and #notifyAll to create a framework with concurrency such as a Thread that does work on an instance of a certain object and other threads are waiting to work on it.
A thread "dies" out if the run function is over, but if you want to stop the thread immediately, use #interrupt.

Does the waiting thread revisit the code inside synchronized method

I was reading about thread synchronisation and wait/notify constructs from the tutorial. It states that
When wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke Object.notifyAll, informing all threads waiting on that lock that something important has happened.
Some time after the second thread has released the lock, the first thread reacquires the lock and resumes by returning from the invocation of wait.
AFAIK, if there are multiple threads which can compete for the lock when the first thread is awaken by the notify, any one of them can get to own the lock on that object. My question is, if this first thread itself re-acquires the lock, does it have to start all over from the beginning of the synchronized method (which means, it again executes the code before the while loop checking wait() condition) or does it just pause at the wait() line?
// Does the waiting thread come back here while trying to own the
// lock (competing with others)?
public synchronized notifyJoy() {
// Some code => Does this piece of code gets executed again then in case
// waiting thread restarts its execution from the method after it is notified?
while (!joy) {
try {
// Does the waiting thread stay here while trying to re-acquire
// the lock?
wait();
} catch(InterruptedException e) {}
}
// Some other code
}
A method only gets exited when the thread executing it finishes executing its run method, whether by returning normally or having an exception be thrown that goes uncaught within that run method. The only way for your method to not get executed until one of those things above happens is for the JVM to be killed out from under you, with java.lang.System.exit, or if the method is being run in a daemon thread where the JVM is shutting down. There's nothing weird going on here. The thread that waits gives up the lock and goes dormant, but it doesn't somehow leave off executing the method.
The thread awakened from its call to wait never went anywhere; the whole time that the thread was waiting it was still in the wait method. Before it can leave the wait method it first has to acquire the lock that it gave up in order to start waiting. Then it needs to retest whatever condition it needs to check before it can know whether to keep on waiting.
This is why the guarded blocks tutorial tells you that waits have to be done in a loop:
The invocation of wait does not return until another thread has issued a notification that some special event may have occurred — though not necessarily the event this thread is waiting for:
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
(The wording used by the tutorial is misleading; the word "interrupt" should be "notification". Also it is unfortunate that the tutotial code shown eats the InterruptedException without setting the interrupt flag, it would be better to let the InterruptedException be thrown from this method and not catch it at all.)
If the thread "started over" then this loop wouldn't be required, your code would start at the beginning of the method, acquire the lock, and test the condition being waited on.
Thread execution starts directly after the call to wait. It does not restart the block from the beginning. wait() can be roughly implemented similar to
public void wait() {
release_monitor();
wait_monitor();
acquire_monitor();
}
This is no where near how it is actually implemented, it is just a rough idea of what goes on behind the scenes. Each Object has a monitor associated with it that can acquired and released. Only one thread can hold the monitor at a time and a thread can acquire a monitor recursively with no issue. A call to wait on an Object releases the monitor allowing another thread to acquire it. The waiting thread then waits until it is woken up by a call to notify/notifyAll. Upon being woken up the waiting thread waits again to require the Object's monitor and returns to the calling code.
Example:
private Object LOCK = new Object;
private int num = 0;
public int get() {
synchronized( LOCK ) {
System.out.println( "Entering get block." );
LOCK.wait();
return num;
}
}
public void set( int num ) {
synchronized( LOCK ) {
System.out.println( "Entering set block." );
this.num = num;
LOCK.notify();
}
}
"Entering get block." will only be printed once for each call to get()

Resources