Is Thread.interrupt really stops program execution? - java

I am stopping the thread execution using Thread.interrupt but the thread execution won't stopped . It's still running .
Example :
Thread t = new Thread(new Runnable() {
#Override
public void run() {
int i = 0;
while(i<10000){
if(Thread.currentThread().isInterrupted()){
System.out.println("Thread Interrupted but it still running");
}
System.out.println(++i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
t.interrupt();
I can't check Thread.isInterrupted() then if thread is interrupted break out of the loop . I can't do this . Here , I am just showing the sample example .
My doubt is Thread.interrupt is only sets interrupted flag only or it really stops the execution .
any help regarding this will be appreciated.
How can I stop the thread execution or kill the running thread?

Thread.interrupt() will genuinely interrupt an operation that actually checks for that state (either, say, an interruptible I/O operation or else some user code that explicitly checks isInterrupted() as in principle you do in the code you quote).
In the specific example you quote, you need to bear in mind that:
each processor core executes in the order of billions of instructions
per second;
process switching occurs in the order of tens to hundreds
of times per second.
In other words, your task of decrementing a counter 10,000 times is something that happens so fast that to all intents and purposes it will barely register as being an "interruptible task". In practice, either all 10,000 decrements will happen before the other thread has chance to call interrupt() or they won't.

If the thread is blocked on wait, sleep or join then InterruptedException is thrown otherwise interrupted status is set.
Interrupted status is cleared if Thread.interrupted is called.
Thread.isInterrupted does not clear the interrupted status.
If the thread's interrupted status is set and this thread calls wait, sleep or join then interrupted status is cleared and InterruptedExcepion is thrown.

It only sets the flag UNLESS an interruptable statement (e.g. sleep, wait) was executing at the time. Now you should be able to work out how to stop the thread, by dealing with both situations.
I can't check Thread.isInterrupted() then if thread is interrupted
break out of the loop . I can't do this .
Why not?
E.g.
while(i<10000){
if(Thread.currentThread().isInterrupted()){
System.out.println("Thread Interrupted but it still running");
return; // HERE
}
System.out.println(++i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
return; // HERE
}
}

My doubt is Thread.interrupt is only sets interrupted flag only or it really stops the execution.
It does the former ... or throws an "interrupted" exception in certain circumstances.
How can I stop the thread execution or kill the running thread?
In general, you cannot safely stop or kill a running thread that is not checking its interrupted flag. There are some deprecated methods on the Thread class, but you should avoid using them as they are manifestly unsafe. (To understand why the Thread method javadocs ... and the FAQ that it links to.)

Related

When to call Thread.currentThread().interrupt() and when not to call?

From multiple articles around the internet it's advised not to swallow InterruptedException. It makes much more sense to do it with thread pool executors something like this when I'm going to reuse the same thread.
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
printNumbers(); // first call
printNumbers(); // second call
});
Thread.sleep(3_000);
executor.shutdownNow(); // will interrupt the task
executor.awaitTermination(3, TimeUnit.SECONDS);
}
private static void printNumbers() {
for (int i = 0; i < 10; i++) {
System.out.print(i);
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // preserve interruption status
break;
}
}
}
Code sample above from DZone.
But in the case of creating new thread each time like:
Object LOCK = new Object();
public void doSomeJob() {
myThread = new Thread(new Runnable() {
public void run() {
try {
synchronized(LOCK) {
System.out.println("Inside run");
LOCK.wait();
}
} catch(InterruptedException ignored){}
}
}
}
Do I still need to call Thread.currentThread().interrupt();? Will that make any sense?
Good references:
https://codepumpkin.com/interrupt-interrupted-isinterrupted-java-multithreading/
http://michaelscharf.blogspot.com/2006/09/dont-swallow-interruptedexception-call.html
I will give an answer based on section 7.1.2 of great book Concurrency in Practice by Brian Goetz.
In your first example you use ExecutorService. ExecutorService manages it's own threads. You are not the owner of those Threads so you do not know what interruption means to them ( for example ThreadPool might choose to kill Threads that were interrupted and create new ones). That is why you should preserve interruption status when you submit a cancelable task to this pool. This citation applies to this case:
Tasks do not execute in threads they own.They borrow threads owned by a service such as a thread pool. Code that
doesn't own the thread (for a thread pool, any code outside of the thread pool implementation) should be careful to
preserve the interrupted status so that the owning code can eventually act on it, even if the "guest" code acts on the
interruption as well. (If you are housesitting for someone, you don't throw out the mail that comes while they're away - you save it and let them deal with it when they get back, even if you do read their magazines.)
In the second case you manage an instance of Thread manually. So you are the owner of it. Therfore you decide what interruption means to this Thread and you do not have to preserve the Interruption Status in the second case if you do not want to apply any Thread Interruption Policy for it :
What you should not do is swallow the InterruptedException by catching it and doing nothing in the catch block, unless your code is actually implementing the interruption policy for a thread
Note also that Thread Interruption Policy is different than Task Cancellation Policy :
Thread Interruption Policy - defines how Thread reacts to interruption (for example ThreadPool might kill Thread that was interrupted and create a new one). It is defined by the owner of the thread.
Task Cancellation Policy - defines how task reacts to cancellation. Cancellation is usually implemented with interruption. The one who implements the task chooses if task in responsive to interruption. This is easily achieved if your task calls methods that throw InterruptedException. Or you can check the interruption flag of the Thread by calling Thread::isInterrupted (for example in a loop). The implementor of the task chooses how to handle this.
Also you should not take any assumptions of Thread Interruption Policy (if you are not the owner of the Thread). That is why preserving Interruption Status or rethrowing InterruptedException is considered a good practice.
If your lock comes from java.util.concurrent.locks.Lock and is interruptible (using .lockInterruptibly()), it does make sense to interrupt the process so everything might be interrupted and cancelled.
Read chapter Implementation Considerations from the documentation.
But if your lock is non-interruptible (using .lock()) it will not make sense as you won't be able to interrupt the lock.
In your case, you're using wait() which is interruptable as written here, and will throw an InterruptedException.
The explanations in DZone link https://dzone.com/articles/understanding-thread-interruption-in-java in your question are very detailed. Thread.currentThread().interrupt(); raises back interrupted exception status which is cleared before by blocking methods (sleep). It is done to ensure second loop interrupted too (it will catch the exception as it is on the same thread).
Before I finish, I wanted to emphasize on an important detail about
what happens to a thread’s interruption status when a blocking code
responds to interruption by throwing InterruptedException. I had left
out the detail till now to avoid confusion.
Before a blocking code throws an InterruptedException, it marks the
interruption status as false. Thus, when handling of the
InterruptedException is done, you should also preserve the
interruption status by callingThread.currentThread().interrupt().
Let’s see how this information applies to the example below. In the
task that is submitted to the ExecutorService, the printNumbers()
method is called twice. When the task is interrupted by a call
toshutdownNow(), the first call to the method finishes early and then
the execution reaches the second call. The interruption is called by
the main thread only once. The interruption is communicated to the
second execution of the printNumber() method by the call to
Thread.currentThread().interrupt() during the first execution. Hence
the second execution also finishes early just after printing the first
number. Not preserving the interruption status would have caused the
second execution of the method to run fully for 9 seconds.
Where to use Thread.currentThread().interrupt(); depends on your code, second example is not complete to understand the need for it.

Does an InterruptException cause the thread to stop

I thought that the currently executing Thread will be stooped if the exception is thrown. Bu when I was going throught a java test a came across with the question:
Under which conditions will a currently executing thread stop?
When an interrupted exception occurs.
When a thread of higher priority is ready (becomes runnable).
When the thread creates a new thread.
When the stop() method is called.
A. 1 and 3
B. 2 and 4
C. 1 and 4
D. 2 and 3
The right answer was B, but what then happens if the exception is thrown? I thought the thread is terminating.
The right answer was B
No it wasn't. None of the answers given is correct.
but what then happens if the exception is thrown? I thought the thread is terminating.
No. The thread catches InterruptedException from whatever method it was calling that can throw it, for example Thread.sleep(). If it doesn't call such a method, nothing happens at all.
When a method throws InterruptedException, it is telling that it is a blocking method and that it will make an attempt to unblock and return early -- if you ask nicely.
When you try to interrupt a thread by calling interrupt() on the thread instance, it merely sends a signal. It depends on the actual thread to respond to that signal. Methods like Thread.sleep() and Object.wait() can look for this signal and make an attempt to stop what it is doing and return early and indicate its early return by throwing InterruptedException. So it's usually an acknowledgement from some blocking methods to the interrupt() request sent by some other thread.
Thread t = new Thread(() -> {
try {
Thread.sleep(5000); // Thread.sleep() allows a cancellation mechanism
} catch (Exception e) {
System.out.println("interrupted by some one else from outside");
}
});
t.start();
try {
t.interrupt();
t.join(); // waiting for the thread to finish its execution
System.out.println("back in main");
} catch (InterruptedException e) {
System.out.println("interrupted");
}
Output :
interrupted by some one else from outside
back in main
But if you have thread like this
Thread t = new Thread(() -> {
try {
for(int i=0;i<1_000_000;i++){
System.out.println(i);
}
} catch (Exception e) {
System.out.println("interrupted by some one else from outside");
}
});
Calling interrupt() on above thread will not do anything useful because we're not looking for the signal, so thread will print all numbers and join the main thread as if nobody ever asked it to stop doing what it is doing.
In case you want to learn more about this InterruptedException, I highly recommend thisBrian Goetz's article from IBM Developer Works
A thread, t, will stop if some other thread calls t.stop(), but please don't ever do that! One thread should never force another thread to do anything. Threads should always cooperate. Any program that calls t.stop() is very likely to contain bugs that you won't be able to fix without getting rid of the stop() call.
A thread will terminate (which is a kind of stop, right?) if some external process kills the JVM.
A daemon thread will terminate if the JVM shuts down because there are no non-daemon threads left to keep it alive.
A thread may stop or terminate because of the action of an attached debugger.
The only other reason why a thread will stop (and terminate) is if its run() method completes. A method can either complete normally by returning, or it can terminate abnormally (i.e., an exception is thrown and not caught within the method call.) A thread will terminate if its run() method completes in either way.
An InterruptedException doesn't affect a thread any differently from any other exception. If the thread catches the exception, then the thread will continue to run, but if no method in the thread catches it, then the thread's run() method will abnormally complete, and the thread will terminate (stop).

Best way to handle exception when joining a thread

For some reason I am confused over the following:
Assume that I have Thread A that absolutely needs to execute after Thread B has completed its processing.
A way to do this would be by Thread A joining Thread B.
Trivial example:
public class MainThread {
public static void main(String[] args){
Thread b = new Thread (new SomeRunnable(args[0]));
b.start();
try {
b.join();
} catch(InteruptedException e) {
}
// Go on with processing
}
}
My question is the following: What is the proper way to handle the exception in such a case?
In various example I have seen, even in text-books, the exception is ignored.
So if Thread A needs to be sure that Thread B is completely finished before proceding, if I end up in the catch due to an exception, can it be the case that Thread B may still actually be runnable/running? So what is the best way to handle this exception?
First of all you must understand what causes this exception to be thrown. Calling stop() on a thread is currently deprecated, instead when you want to stop a thread you are interrupting it by calling thread.interrupt(). This has no impact on a thread (!), the thread must explicitly check interrupted flag once in a while and stop processing gracefully.
However if the thread sleeps, waits on a lock or on another thread (by using join() like in your example) it cannot check this flag immediately or often enough. In these cases JVM will throw an exception from blocking method (let it be join()) signalling your thread that someone just tried interrupting it. Typically you can ignore that exception (meaning - do not log it) - it's the side effect that matters. For example breaking out of the loop:
public void run() {
try {
while(!isInterrupted()) {
Thread.sleep(1000);
//...
} catch(InterruptedException e) {
//no need to log it, although it's a good idea.
}
}
It's not a problem that you didn't log that exception - but you escaped from the loop, effectively terminating the thread.
Now back to your question. When your Thread A is interrupted it means some other thread requested terminating it, probably because the whole JVM shuts down or web application is being undeployed. In this case you shouldn't be doing anything except cleanup.
Moreover it most likely means Thread B is still running. But what JVM is trying to say is: "Danger! Danger! Stop waiting for whatever you were waiting for and run!".
What is the proper way to handle the exception in such a case?
Any time you get an InterruptedException the current thread should consider itself to be interrupted. Typically, that means that the thread should clean up after itself and exit. In your case, the main thread is being interrupted by another thread and should probably interrupt the Thread a that it started in turn, and then quit.
Although it is up to you whether the interrupt should be ignored I would suggest that it is a bad practice. If you were using the interrupt as some sort of signal to the thread then I would instead set some volatile boolean flag.
In terms of best practice when catching InterruptedException, typically I do:
try {
...
} catch(InterruptedException e){
// a good practice to re-enable the interrupt flag on the thread
Thread.currentThread().interrupt();
// in your case you probably should interrupt the Thread a in turn
a.interrupt();
// quit the thread
return;
}
Since catching the InterruptedException clears the interrupt flag for the thread, it is always a good idea to re-enable the interrupt flag in the catch block.
In various example I have seen, even in text-books, the exception is ignored.
Indeed. It is very bad practice to ignore any exception but it happens all of the time. Don't give into the dark forces!
can it be the case that Thread B may still actually be runnable/running?
Thread B can certainly still be running. It is the main thread that is calling the join() that has been interrupted.

What does java.lang.Thread.interrupt() do?

Could you explain what java.lang.Thread.interrupt() does when invoked?
Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)
Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.
Polling occurs via the Thread.interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.
EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.
Object.wait(), Thread.sleep(), and Thread.join()
Most java.util.concurrent structures
Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.
EDIT (from #thomas-pornin's answer to exactly same question for completeness)
Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop() that is more like shooting the thread with an assault rifle.
What is interrupt ?
An interrupt is an indication to a
thread that it should stop what it is
doing and do something else. It's up
to the programmer to decide exactly
how a thread responds to an interrupt,
but it is very common for the thread
to terminate.
How is it implemented ?
The interrupt mechanism is implemented
using an internal flag known as the
interrupt status. Invoking
Thread.interrupt sets this flag. When
a thread checks for an interrupt by
invoking the static method
Thread.interrupted, interrupt status
is cleared. The non-static
Thread.isInterrupted, which is used by
one thread to query the interrupt
status of another, does not change the
interrupt status flag.
Quote from Thread.interrupt() API:
Interrupts this thread. First 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.
If this thread is blocked in an I/O
operation upon an interruptible
channel then the channel will be
closed, the thread's interrupt status
will be set, and the thread will
receive a ClosedByInterruptException.
If this thread is blocked in a
Selector then the thread's interrupt
status will be set and it will return
immediately from the selection
operation, possibly with a non-zero
value, just as if the selector's
wakeup method were invoked.
If none of the previous conditions
hold then this thread's interrupt
status will be set.
Check this out for complete understanding about same :
http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.
It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.
It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.
For completeness, in addition to the other answers, if the thread is interrupted before it blocks on Object.wait(..) or Thread.sleep(..) etc., this is equivalent to it being interrupted immediately upon blocking on that method, as the following example shows.
public class InterruptTest {
public static void main(String[] args) {
Thread.currentThread().interrupt();
printInterrupted(1);
Object o = new Object();
try {
synchronized (o) {
printInterrupted(2);
System.out.printf("A Time %d\n", System.currentTimeMillis());
o.wait(100);
System.out.printf("B Time %d\n", System.currentTimeMillis());
}
} catch (InterruptedException ie) {
System.out.printf("WAS interrupted\n");
}
System.out.printf("C Time %d\n", System.currentTimeMillis());
printInterrupted(3);
Thread.currentThread().interrupt();
printInterrupted(4);
try {
System.out.printf("D Time %d\n", System.currentTimeMillis());
Thread.sleep(100);
System.out.printf("E Time %d\n", System.currentTimeMillis());
} catch (InterruptedException ie) {
System.out.printf("WAS interrupted\n");
}
System.out.printf("F Time %d\n", System.currentTimeMillis());
printInterrupted(5);
try {
System.out.printf("G Time %d\n", System.currentTimeMillis());
Thread.sleep(100);
System.out.printf("H Time %d\n", System.currentTimeMillis());
} catch (InterruptedException ie) {
System.out.printf("WAS interrupted\n");
}
System.out.printf("I Time %d\n", System.currentTimeMillis());
}
static void printInterrupted(int n) {
System.out.printf("(%d) Am I interrupted? %s\n", n,
Thread.currentThread().isInterrupted() ? "Yes" : "No");
}
}
Output:
$ javac InterruptTest.java
$ java -classpath "." InterruptTest
(1) Am I interrupted? Yes
(2) Am I interrupted? Yes
A Time 1399207408543
WAS interrupted
C Time 1399207408543
(3) Am I interrupted? No
(4) Am I interrupted? Yes
D Time 1399207408544
WAS interrupted
F Time 1399207408544
(5) Am I interrupted? No
G Time 1399207408545
H Time 1399207408668
I Time 1399207408669
Implication: if you loop like the following, and the interrupt occurs at the exact moment when control has left Thread.sleep(..) and is going around the loop, the exception is still going to occur. So it is perfectly safe to rely on the InterruptedException being reliably thrown after the thread has been interrupted:
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
break;
}
}
Thread interruption is based on flag interrupt status.
For every thread default value of interrupt status is set to false.
Whenever interrupt() method is called on thread, interrupt status is set to true.
If interrupt status = true (interrupt() already called on thread),
that particular thread cannot go to sleep. If sleep is called on that thread interrupted exception is thrown. After throwing exception again flag is set to false.
If thread is already sleeping and interrupt() is called, thread will come out of sleeping state and throw interrupted Exception.
Thread.interrupt() sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted() can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
A very good referance: https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
Thread.interrupt() method sets internal 'interrupt status' flag. Usually that flag is checked by Thread.interrupted() method.
By convention, any method that exists via InterruptedException have to clear interrupt status flag.
public void interrupt()
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.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.
Throws:
SecurityException - if the current thread cannot modify this thread
I want to add one or two things to the above answers.
One thing to remember is that, calling on the interrupt method does not always cause InterruptedException. So, the implementing code should periodically check for the interrupt status and take appropriate actions.
Thread.currentThread().isInterrupted() can also be used to check the interrupt status of a thread. Unlike the Thread.interrupted() method, it does not clear the interrupt status.

Java thread interrupts and joins (thread is still alive after join)

I'm trying to figure out some behavior. I've got some code that spawns one thread. It waits some amount of time, and then interrupts it, joins it and then exits the method.
.
.
.
try {
Thread.sleep(processForMillis);
}
catch (InterruptedException ex) {
// Won't happen, ignore.
}
for (Thread t : threads) {
logger.debug("Interrupting Thread " + t.getName());
t.interrupt();
}
for (Thread t : threads) {
try {
t.join(1000L);
logger.debug("Joined Thread " + t.getName());
logger.debug("isAlive? " + t.isAlive());
}
catch (InterruptedException ex) {
// this will never happen
logger.debug("InterruptionException while joining, but didn't expect it.");
}
}
} // end of method
I am currently running this with just one thread. I can see in my logs that usually, isAlive() will be false after the join, but sometimes it is still alive. The thread is sitting in a while loop:
while(!Thread.currentThread().isInterrupted()){
.
// do some blocking io stuff here
}
So what I suspect is happening is we are interrupting the thread while it is reading/processing the inputstream (blocking io) and it is taking more than the time it takes to hit the while conditional and finish the join.
So my question is, what happens to the thread?
It is no longer referenced and the thread can be garbage collected, but none of of the resources are cleaned up properly, and that seems bad. Is there a better pattern for this besides switching to NIO?
interrupt() just sets a flag on the thread that it has been interrupted. Many blocking calls does not unblock when this occurs, meaning the thread is pretty much unaffected by the interrupt and keeps doing its thing(e.g. blocking on an InputStream).
I'm guessing in some cases the thread doesn't unblock and hit your while condition in the given join timeout (1 second here), in other cases the blocking call happens to complete within the timeout and the thread ends.
As long as a thread is running it will still have a reference and not be garbage collected.
If the blocking call never unblocks - which could happen if it reads from e.g. a dead tcp sockets whos other end has silently disappeard, the thread might never end.
In addition to the nos's answer, to interrupt a blocking IO call you can close() its stream

Categories