Thread interrupt() does not interrupt thread - java

For some reason, when iterating over a list of threads and interrupting all of them, none of them executes the catch block with InterruptedException.
In the following repository: https://github.com/ranisalt/LiuThread
I have two threads, each of them has executor services and one of them holds readers, the other reads writers. Writers should spawn every 100 ms, write to the buffer and quit/stop/whatever just don't write again. Readers are 4 threads that try to read and, if they can, they should quit too, so there's space for another reader.
I have 100 of each (reader and writer) and if they fail to read or write, they wait 60 seconds.
Then, I have a coordinator thread that keeps testing if the buffer is empty (and interrupts the writers) or full (interrupts the readers), so they never should get to wait 60s. The buffer knows its state.
The problem is, for some reason, this snippet:
for (ThreadAzul azul : threadsAzuis) {
azul.interrupt();
}
Is NOT interrupting the thread! I have used println to see if is getting interrupted:
try {
sleep(60000);
System.out.println(this.getName() + " foi dormir");
} catch (InterruptedException e) {
System.out.println(this.getName() + " foi interrompido");
}
But this NEVER gets written. What is the reason for interrupt() not making the catch block execute?

Inside the main method you are invoking run() on your Thread so you never start a new Thread but instead run its code within the initial main thread. So invoking interrupt on the Thread instance you never have started will not interrupt the main thread which is actually executing the code.
The same error repeats when you submit a Thread instance to an Executor. The executor will execute the run method of the Thread instance because Thread implements Runnable but the Executor will do so within its own managed Thread but not within the Thread represented by the instance you have created but never started.
So again, invoking interrupt on the Thread instance you never have started will not interrupt the thread actually executing the code.
Generally you should not mix Thread and Executor usage. Decide for one way, dealing with Threads manually or using ExecutorSevices.
And when you are using Threads you must start them using the start() method, not invoking the run() method.

Threads only get interrupted during interruptible operations, for example Thread.sleep(), Thread.wait(), and some I/O calls (not all).

Setting the interruptionflag, does not interrupt the Thread. The Thread just ends when it checks, if it is supposed to end. So just give the Thread the chance to check isInterrupted(), or interrupt it while it is sleeping or waiting.
If you have a long-term method in run(), interrupt() will not work. You have to implemet a regularly check or another workaround.

Related

How to stop / kill multiple threads after a Time-Out value in java

I want to stop / kill all Threads (Runnables) started by Main after a given timeout. I tried to do as mentioned below. But it is not working as expected. Apart from that, I tried with the Thread.interrupt() but the results is negative. I tried thread.stop(). It is working but deprecated.
Can anyone give some idea on this?
Note : I'm focusing on a solution for Runnables not Callables. And I'm trying to do this bymodifying only the client code (Main). Not the Threads (Supplier)
Main
Thread roxtoursThrd = new Thread(new Supplier("roxtours", 1));
Thread bluevacationsThrd = new Thread(new Supplier("bluevacations", 1));
Thread elixerThrd = new Thread(new Supplier("elixer", 1));
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
taskExecutor.execute(roxtoursThrd);
taskExecutor.execute(bluevacationsThrd);
taskExecutor.execute(elixerThrd);
taskExecutor.shutdown();
// taskExecutor.shutdownNow(); // This is also not stopping threads. They continue.
try {
taskExecutor.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
Supplier.java
public class Supplier implements Runnable {
public Supplier(String name, int count) {
this.name = name;
this.count = count;
}
#Override
public void run() {
try {
// Some time consuming operations (URL Connections, XML Decoding, DB Queries etc etc) are goes in here.
} catch (Exception e) {
e.printStackTrace();
}
}
String name = null;
int count = 0;
Logger logger = Logger.getLogger(Supplier.class);
}
Making the executor's tasks respond to interruption will require changing the code for the Suppliers. Interruption is cooperative; the thread being interrupted gets a flag set on it, but it's up to the thread to decide how to handle it. If your Runnable doesn't act on it, as in your example, then nothing happens, the thread just keeps on executing.
The Executor can only cancel threads that respond to interruption, see the API documentation for ExecutorService.shutdownNow:
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
A thread can check its flag with the Thread#isInterrupted method. Your Runnable task should check Thread.getCurrentThread().isInterrupted().
If a thread is waiting or sleeping when the interrupted flag is set then an InterruptedException will be thrown and the flag will be cleared.
Do not use Thread#setDaemon(true) unless you're prepared for those threads to disappear suddenly with no warning and no chance to clean up pending tasks when the rest of the application shuts down.
The other option is the deprecated Thread#stop method, which causes ThreadDeath to be thrown. Unlike interruption, this is not cooperative, and it's between difficult and impossible to write code that can predictably and cleanly terminate when this exception occurs, because ThreadDeath can be thrown anywhere, unlike InterruptedException, which is much more manageable since it is only thrown from specific blocking calls.
Use shutdownNow() instead of shutdown().
The shutdown() will initiate the shutdown and it will not accept any new tasks but you never know when the threads will be actually stopped.
The shutdownNow() will immediately attempts to stop all the active threads and this will return all the active threads which are awaiting for execution.
Again there is no guarantee that all the threads will be stopped immediately (Threads will go for a graceful shutdown and it may take time based on the task given to the thread). We have to use either of the below methods to wait till all the threads are completed its execution.
executor.awaitTermination(...);
or
while (! executor.isTerminated()) {
// Sleep for few milliseconds...
}
Refer the doc: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdown%28%29
Your thread's run method is not blocking, hence it does not run into a situation where an InterruptedException is thrown.
When a Thread is inerrupted, besides throwing an exception if it is blocking, it also has its interrupted status set, that is to say the method Thread#isInterrupted() returns true. Also, the method Thread#interrupted also returns true, but with the latter the interrupted status of the thread is cleared.
In your example you are not blocking nor are you checking the threads inerrupted status.
EDIT: Since you are not checking to see if the thread is interupted nor are you blocking, then you can't stop the threads explicitly, but you can stop them by making them daemon threads and then when your main thread (which is a user thread) finishes, all the other daemon threads will stop. Main difference between daemon thread and user thread is that as soon as all user thread finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution.
If you want to interrupt threads, you have to provide interruption entrance point. Sleep for a very short time, for example, then catch and handle InterruptionException.
Next what you can do is make use of isInterrupted() method in every iteration and the handle that as well.
Other approach would be to make all the threads daemons with setDaemon(), as they would be killed after main thread finishes, but this would be useful only if main was to be stopped.
In response to your edit/updated question:
excerpt from shutdownNow() documentation
There are no guarantees beyond best-effort attempts to stop processing
actively executing tasks. For example, typical implementations will
cancel via Thread.interrupt(), so any task that fails to respond to
interrupts may never terminate.
So either you prepare you application to work as multi-threaded or you stick to single thread.
Also, see How do you kill a thread in Java?.
And the most important link from the question above: http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

What is the difference between wait/notify and wait/interrupt?

synchronized (Foo.class) {
while (someCondition) {
try {
Foo.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
It seems that this thread both wakes when some other thread call interrupt() or notify() on this thread. Are there any differences between the two?
--EDIT--
I know one is for notifying an object, the other interrupts a thread. But both of these lead to the same consequence, that is, this thread is waken up, so what I want to ask is how these 2 situations' consequences are different from each other.
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. (Alternatively a thread can call notifyAll, which wakes up all the threads waiting for that monitor, then they all contend for the monitor, then the losers go back to waiting.) That's why the target of the call is different, the notification is made to the monitor, which tells the scheduler to pick a thread to wake up.
Unlike notify, interruption targets a specific thread. And interruption does not require that the interrupted thread be waiting on a monitor. For a thread to call wait on a monitor it has to have acquired that monitor first, then wait releases that monitor until the thread is done waiting or is interrupted.
Oracle's recommendation is to use interruption only for cancellation. Also the classes in java.util.concurrent are designed to use interrupt for cancellation.
In your example interruption won't be very effective, because control doesn't leave the while loop, the thread still has to check the condition it's waiting on, and there's no check in the while loop condition for whether the interrupt flag is set. It's likely the thread that's interrupted will go right back to waiting.
In order to make this code quit once it's interrupted, rather then return to waiting, add a check for the interrupted flag status to the loop condition, and have the catch block set the interrupt flag (which gets reset when the exception is thrown):
synchronized (Foo.class) {
while (someCondition && !Thread.currentThread().isInterrupted()) {
try {
Foo.class.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Basically, you are not looking for a text book difference but difference in their uses cases.
As folks have already pointed out, waking up the thread is not the only consequence but calling t1.interrupt() from Thread t2 for t1 will cause an InterruptedException in thread t1 and that is a big difference between Object.notify() and Thread.interrupt().
You should understand that its method Object.wait() which throws checked InterruptedException and forces you to handle it. Object.wait.
InterruptedException - if any thread interrupted the current thread
before or while the current thread was waiting for a notification. The
interrupted status of the current thread is cleared when this
exception is thrown.
Then you should consult this question to get an idea about handling this exception.
Difference between the two lies in the fact that one is for inter thread communication for usual logical programing stuff ( wait & notify ) and other one ( interrupt) is for preemptive thread cancellation / termination even in cases of blocking operations. You have to note that Java doesn't provide any mechanism to preemptively cancel a thread so you have to use interrupt mechanism for that purpose ( Obviously, if that is needed in your case. You might very well ignore this Exception if not applicable in your case).
Java doesn't restrict your actions after InterruptedException and you can do anything you want but using it for things other than implementing Thread Cancellation Policy is not advised. Thread Cancellation Policy is often ignored and less discussed area when programmers write multi threaded programs and that is why you might be finding it difficult to understand the use case.
What does an API method like BlockingQueue.put(..) is trying to tell you by throwing InterruptedException is that even its blocking operation can be preemptively terminated. Its not necessary that all blocking API methods will provide you that facility.
Cancellation/Termination of a thread using Thread.interrupt() is not a forceful but cooperative mechanism and is just a request not an order.
Your use of e.printStackTrace(); is strongly discouraged since this is usually not an error, if intention is to log it as an error.
Hope it helps !!
Wait method is used to suspend a current thread on an object.
Wait method is not from thread class but from java.lang.Object
Notify method is used to wake the thread waiting on the object.
Notify method is not from thread class but from java.lang.Object.
Interrupt method is used to to indicate the current thread that is
should stop current job execution and can start other job.
Interrupt method is from thread class.
Let see the real life example:
Consider Telephone as Object , Person as Thread.
Suppose for instance A person is using Telephone and B person also wants to use the telephone but as A person i.e (Thread 1) is busy using it unless the work is done acquires a lock on telephone Object now B i.e(Thread 2) tries to use Telephone but as A has acquired lock on it B it goes into wait state until lock is released.
If Telephone object calls wait method it will restrict current thread
which want to use Telephone and it will go into wait state.
If Telephone object calls notify it will signal the thread waiting on
it to acquire lock and proceed with the intended work.
If Person A(Thread 1) is using Telephone object and is in some task
but interrupt method is called then A will be signaled to stop with
current task and may need to do some other task assigned.

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.

Confusion on Wait ,Notify and Sleep

I have a simple program which I am finding very confusing. The code snippet is as follows:
class Processor{
public void produce() Throws InterruptedException{
synchronized(this){
System.out.println("Producer Running...");
wait();
System.out.println("Resumed");
}
}
public void consume() Throws InterruptedException{
synchronized(this){
Thread.Sleep(2000);
System.out.println("Consumer Running... Press return key to return");
scan.nextLine();
notify();
Thread.sleep(5000);
}
}
Now my question is that , when we call wait() in the "produce" method the execution is immediately transferred to the "consume" method. (produce and consume are executed in separate threads). But when the notify(); is called in the "consume " method ,the execution does not immediately transfer. It waits for Thread.sleep(5000) to complete . why is this so ?
Well, the reason is quite simple.
When a thread calls wait() on certain object it goes into a waiting state and it stops executing (it is removed from scheduling). When waiting a thread releases all the monitors it has taken (and it needs to regain them after waking up)
When a thread calls notify() on certain object it wakes up another thread waiting over it, but it does not go into a waiting state itself, so it keeps running.
After your producer thread calls notify it keeps running and performing a five seconds sleep. While sleeping a thread retains all monitors that it has taken (you are inside a synchronized(this) block hence you have a monitor for "this" object). Scheduler cannot run the consumer thread that was just notified since it needs to readquire the monitor before resuming, and it wont be freed until your producer thread stops sleeping and gets out of the synchronized block
Although you seem to be missing some code needed for me to explain completely accurately, I'll do my best to provide an explanation that would be applicable even if my guess was incorrect.
wait() and notify() are methods called on a mutex object -- in this case, this.
wait() causes the currently executing thread to pause and give up that mutex (I think it's just the mutex that wait() is called on, could be all of them. Not sure), after which another thread can acquire the mutex and start executing. This is why you observe an immediate transfer of control when wait() is executed.
When notify() is called on a mutex, a thread waiting on that mutex wakes up and attempts to acquire the lock. However, it cannot do so until the lock is available -- in this case, until the lock (this) is released by the thread that calls notify() (the consumer thread). The mutex is only released once the consumer thread exits from the synchronized block, which is after the Thread.sleep(5000); call in your code. sleep() does not release any mutexes that the current thread has acquired, so the first thread has to wait until the second has finished sleeping and exited the synchronized block.
That is why wait() transfers control immediately, while notify() (in this case) has the currently executing thread finish its method before the formerly waiting thread can continue execution.
Assuming that you are calling both methods using the same object from difference threads.
If you want to don't wait 5000 miliseconds, use wait(5000) instead of Thread.sleep(5000).
The notify method, take one (random) previously waiting thread, that is waiting to acquire the lock (of an object) that the running/current thread has taken before, and mark it to resume as soon the current thread release the lock.
In your this case, it will release the lock and soon the Thread.sleep(5000) finish and leave the synchronized block.
Be aware, if you call produces or consume with diferents objects things will go totally diferent. I strongly suggest to read this article.
Hope it helps! As the good answers below!
The reason is that Thread.sleep(5000L) does not release the lock on the object's monitor while it's waiting, contrary to wait(5000L). This is specified in the Javadoc for Thread.sleep() :
... The thread does not lose ownership of any monitors.
Whereas the javadoc for Object.wait() specifies:
... This method causes the current thread (call it T) to place itself
in the wait set for this object and then to relinquish any and all
synchronization claims on this object...

How can i call the thread itself?

Lets say i am in the main method calling a process. Now if this process is stuck or taking too long, normally one can interupt it by interupting the thread.
But incase i have it implemented in the main method not in any external thread, how can i call that current thread itself for interuption like we call say thread.interupt();
Please back up a second. Thread.interrupt only interrupts wait conditions, not computations. There is no Java construct (except the monitoring/debugging agents) for interrupting a computation.
So, if you want a long-running computation to be interruptible, you have to write it to carefully check for interrupts every so often.
If you want to be able to 'interrupt' from outside the process altogether, you will need to handle signals. That's about the only interpretation I've been able to place on your question about the main thread.
This blog post (not mine) has the basic information. From a handler, you could interrupt, for example, the main thread.
You can let another thread interrupt "you" (main). Like this:
final Thread me = Thread.currentThread();
Thread wake_me_up = new Thread(){
#Override
public void run(){
//InterruptionException try catch omitted.
Thread.sleep(200);
me.interrupt();
}
};
wake_me_up.start();
try{
go_into_cave();
}catch(InterruptedException e){
//I got interrupted
System.out.println("thank you, you saved my life");
}
go_home();
While I find it hard to read...
In the main method, you'll have a reference to all Threads. Just get the right reference and do something like this
someThread.interrupt();
Make sure you don't forget to check if the Thread that is running got the flag to interrupt set true.
For example, in the middle of it's method, it needs to be checked if itself isInterrupted() by some Thread else
if(Thread.currentThread().isInterrupted()){
doSomeStuff();
}
You can create a new Thread and call your process from inside the new Thread. Interrupt this thread and catch the exception as per your logic.
I am not sure how to do it only form within the main method, but if your process call is called through a method, just call this method from a new thread and put up a timer in the main method. Once the timer expires, interrupt that thread and you're good to go.
If you're trying to kill the process, because it's hung, why are you even worrying about the thread? Runtime.exec() returns a Process object, which you can use to destroy the subprocess. You should be able to:
Spawn the subprocess, saving the Process object.
Presumably, you're reading the output stream of the process, via what is returned by
Process.getInputStream(). So, continue to do that.
However, spawn a second thread (or use the main thread) to monitor the process. If it
decides that the process has run too long, it can kill it via Process.destroy().
At that point, the first thread should get an EOF or an IOException (stream closed) on
the process's output stream.

Categories

Resources