Check if a thread is interrupted? - java

I just want to get know about if this thread is interrupting or not if I'm doing it right?
please give me hint if I'm wrong
public void run(){
int i;
while(!Thread.currentThread().isInterrupted()){
for(i=1;i<=100;i++){
System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);
if(i==3){
Thread.currentThread().interrupt();
gotoInform();
break;
}
try{
Thread.currentThread().sleep(1000);////to sleep the Thread for 1 Second (1000ms)
}
catch(Exception e){
System.out.printf("Error"+e);
}
}
}

This is wrong, because if sleep finds that the thread is interrupted, it will throw an InterruptedException and clear the interrupted flag. You then swallow that exception, suppressing any record that the thread was ever interrupted. Instead, you should write something more like this:
public void run(){
for(int i=1;i<=100;i++){
System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);
if(i==3){
Thread.currentThread().interrupt();
gotoInform();
break;
}
try{
Thread.currentThread().sleep(1000);
}
catch(final Exception e){
e.printStackTrace();
if(e instanceof InterruptedException) {
// just in case this Runnable is actually called directly,
// rather than in a new thread, don't want to swallow the
// flag:
Thread.currentThread().interrupt();
}
return;
}
}
}
(Note: I'm assuming that this is not "real" code, but rather, that you're just trying to learn how thread interruption works. In "real" code, you should almost never need to interrupt the current thread in this way.)

As mentioned before, a thread interrupting itself is pointless (unless used to re-interrupt itself after catching an InterruptedException) . You're basically using the thread's internal interrupted flag as a conditional variable here - which while it may work is not at all what it's supposed to be used for and will be confusing to anyone else who would need to read your code. Use a loop counter instead as suggested above to make the code much cleaner.
Also, your statement:
System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);
is erroneous as it will execute immediately the first time through the loop (when the time is closer to zero seconds).

I just want to get know about if this thread is interrupting or not if I'm doing it right?
#ruakh is correct that it is always a good idea to re-interrupt a thread once InterruptedException is thrown.
However, if the goal of your code is to self-interrupt and no other threads will interrupt the running thread, then you will never get to the sleep() call since break; is called after the thread is interrupted.
If the thread is always just self interrupted then I would just use a flag. Something like:
boolean done = false;
while (!done) {
...
if(i==3){
done = true;
...
}
}
Even though you interrupt your thread, you then call gotoInform() which may call wait()or sleep() itself and cause an InterruptedException. You'll need to make sure that code behaves well and re-interrupts the thread if so.

Related

thread is not interruptible

I'm trying to work on the famous dining philosophers and its quite finished but I'm having a quite hard time trying to interrupt threads.
so as you know in this problem we have 5 threads (philosophers) and the user set an experiment time at which the experiment will end.
worth noticing that I looked multiple answers on StackOverflow.
The first one is from #Konrad Reiche How do you kill a Thread in Java?
/Stackoverflow link
In that particular post, people have stated that using volatile boolean as a flag might work out but I'm afraid that it is stated in the exercise paper that I cant use the volatile boolean to interrupt a thread but I can use it for other purposes. (studying exercise).
The second one is Thread interrupt() does not interrupt thread/Stackoverflow link
yet nothing really helped!.
I will try to provide the necessary code and I hope someone would just point out my mistake/s.
the class Philosopher is public and extends Thread!.
1)First attempt:(might get rejected by the professor if he doesn't want us to use volatile boolean as flag!)
when using volatile boolean like this it works:
private volatile boolean isNotStopped=true;
#Override
public void stopPhilosopher() {
System.out.printf("\n%s will stop.\n",selfPhilosopher.getName());
selfPhilosopher.interrupt();
isNotStopped=false;
}
#Override
public void run() {
while (isNotStopped){//selfPhilosopher is a thread equals to this!.
try {
think();
eat();
} catch (InterruptedException e) {//somehow this was never triggered!.
System.out.printf("%s was interrupted.\n",selfPhilosopher.getName());
}finally {//in the finally block i always get RUNNER, FALSE
System.out.printf("the %s is %s and is interrupted %b.\n", selfPhilosopher.getName(),selfPhilosopher.getState(), selfPhilosopher.isInterrupted());
}
}
}
[UPDATE] on Second attempt:[WORKING]
replacing selfPhilosopher.isInterrupted() with Thread.currentThread().isInterrupted() didn't make any difference as selfPhilosopher=this;
yet I was getting "will stop" from the stopPhilosopher() method but the threads seem to be like zombies keep coming back to life :(
due to the fact that I'm pretty convinced by the opinion of #Konrad Reiche from the first reference provided and the answer of #Nathan Hughes I will stick with using the boolean flag provided by the java isInterrupted() instead of using a volatile flag.
#Override
public void stopPhilosopher() {
System.out.printf("\n%s will stop.\n",selfPhilosopher.getName());
selfPhilosopher.interrupt();
}
#Override
public void run() {
while (!selfPhilosopher.isInterrupted()){//selfPhilosopher is a thread equals to this!.
try {
think();
eat();
} catch (InterruptedException e) {//somehow this was never triggered!.Now it works.
System.out.printf("%s was interrupted from catch clause!..\n",selfPhilosopher.getName());
selfPhilosopher.interrupt();
}
}
}
OUTPUT:
Philosopher2 in seat nr: 2 was interrupted from catch clause!..
When an InterruptedException is thrown, the interrupt flag is cleared. That means the next check your loop makes will indicate the thread is not interrupted and the thread will keep on running. That's what you're seeing when your finally block prints out false for the interrupt flag.
This is described in the API doc for the sleep method:
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
Add this line to the block where you catch an InterruptedException:
Thread.currentThread().interrupt(); // restores interrupt flag
First of all: I favour the volatile boolean flag over isInterrupted(). It is clear, concise and idiomatically established. The necessary structure for isInterrupted() depends more on details (e.g. try/catch in your case because there seems to be a Thread.sleep (or something similar) declaring InterruptedException).
Since try/catch InterruptedException in your example is within the while-loop the interrupt is consumed and need to be resend to selfPhilosopher (which looks a bit dubious). To avoid this put the while-loop into a surrounding try-catch:
try {
while (!selfPhilosopher.isInterrupted()) {
think();
eat();
}
} catch (InterruptedException e) {
System.out.printf("%s was interrupted from catch clause!..\n",selfPhilosopher.getName());
// not necessary anymore: selfPhilosopher.interrupt();
}
The volatile boolean flag would not need resending and could be used in both constellations (while surrounding try/catch as well as while within try).
Additionally: Suppose your class implements Runnable and is not extending Thread then you also need to take care of setting selfPhilosopher at the beginning of run (and nowhere else).

Is it right for a thread to throw an InterruptedException for itself?

This is what I'm doing:
Stopwatch stopWatchToCheckTimeout;
void checkShutDown() throws InterruptedException {
if (stopWatchToCheckTimeout.elapsed() >= MAX_GRACEFUL_TIMEOUT_DURATION) {
throw new InterruptedException("Time to shut down now!");
}
}
public Void mainFancyMethod() {
try {
while(true) {
checkShutDown();
// do fancy work
}
} catch (InterruptedException ex) {
log.debug("Shutting down gracefully");
}
return null;
}
From the java/lang/InterruptedException documentation its not clear to me if by standards it should be another thread that should interrupt or if its okay for a thread to throw this exception for itself?
Whats the best exception to throw for this use-case?
It seems like you are using exceptions in place of control flow. Is there any reason you couldn't just have checkShutDown return a boolean?
boolean timedOut() {
return (stopWatchToCheckTimeout.elapsed() >= MAX_GRACEFUL_TIMEOUT_DURATION)
}
It is correct for a thread to throw an interrupted exception, and in fact threads are usually the sources of InterruptedException.
In your case, I don't think it's appropriate because it has nothing to do with interruption, which is an established thread state. You just want to exit the execution, which could be done in more graceful and performant ways.
TimeLimitExceededException: https://docs.oracle.com/javase/7/docs/api/javax/naming/TimeLimitExceededException.html
From the Docs: "This exception is thrown when a method does not terminate within the specified time limit. This can happen, for example, if the user specifies that the method should take no longer than 10 seconds, and the method fails to complete with 10 seconds. "
This sounds like just what you are after, or?
In the example you posted, you should not throw an InterruptedException.
The Javadoc for InterruptedException states: Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Being interrupted is a result of Thread.interrupt() being called on your running thread, which is not what's happening in the code you posted.
If you do still want to use an exception to break out of your loop, you should use some other exception type. However, an alternative would be to make your check method return true/false, and use that for the condition of your while loop. So instead of this:
try {
while(true) {
checkShutDown();
// do fancy work
}
} catch (InterruptedException ex) {
log.debug("Shutting down gracefully");
}
do something like this:
while (checkIfSafeToContinue()) {
// do fancy work
}

What is purpose of calling interrupt() method again in the following code snippet [duplicate]

Why invoke the method Thread.currentThread.interrupt() in the catch block?
This is done to keep state.
When you catch the InterruptedException and swallow it, you essentially prevent any higher-level methods/thread groups from noticing the interrupt. Which may cause problems.
By calling Thread.currentThread().interrupt(), you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.
Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:
Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.
I think this code sample makes things a bit clear.
The class which does the job :
public class InterruptedSleepingRunner implements Runnable {
#Override
public void run() {
doAPseudoHeavyWeightJob();
}
private void doAPseudoHeavyWeightJob() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
// You are kidding me
System.out.println(i + " " + i * 2);
// Let me sleep <evil grin>
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread interrupted\n Exiting...");
break;
} else {
sleepBabySleep();
}
}
}
protected void sleepBabySleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
The Main class:
public class InterruptedSleepingThreadMain {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new InterruptedSleepingRunner());
thread.start();
// Giving 10 seconds to finish the job.
Thread.sleep(10000);
// Let me interrupt
thread.interrupt();
}
}
Try calling interrupt without setting the status back.
Note:
http://download.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
How do I stop a thread that waits for long periods (e.g., for input)?
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:
Thread.currentThread().interrupt();
This ensures that the Thread will reraise the InterruptedException as soon as it is able.
I would consider it a bad practice or at least a bit risky.
Usually higher level methods do not perform blocking operations and they will never see InterruptedException there. If you mask it in every place you perform interruptible operation, you will never get it.
The only rationale for Thread.currentThread.interrupt() and not raising any other exception or signaling interrupt request in any other way (e.g. setting interrupted local variable variable in a thread's main loop) is the situation where you really can't do anything with the exception, like in the finally blocks.
See Péter Török's answer, if you want to better understand implications of the Thread.currentThread.interrupt() call.
Refer from java doc
If this thread is blocked in an invocation of the wait(), join(),
sleep(long), then its interrupt status will be cleared and it will
receive an InterruptedException.
If this thread is blocked in an I/O operation, 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.
If none of the previous conditions hold then this thread's interrupt
status will be set.
So, if you change the sleepBabySleep() method in #Ajay George Answer to I/O operation or just a sysout, you don't have to set the status back to stop the program. (BTW, they don't even throw InterruptedException)
Just like #Péter Török said => This is done to keep state. (And particular for method that will throw InterruptedException)

Is there any way I can execute the immediate statement after sleep when I have interrupted the thread

Have a look at the following snippet with the comments :
try {
Thread.sleep(20000); // Foo thread sleeps for 20 seconds
System.out.println("After the sleep statement");
} catch(Exception exc) {
exc.printStackTrace();
}
// It has been 12 seconds since the thread went to sleep and....I interrupt
Foo.interrupt(); // exception gets thrown and the code in the catch block gets executed
Is there any way I can execute the next statement after the sleep statement ? I want to awaken the thread at some time and want it to continue it work . Is there any thought/method for this ?
Not sure if this is what you want?
try {
Thread.sleep(20000); // Foo thread sleeps for 20 seconds
System.out.println("After the sleep statement");
} catch(InterruptedException exc) {
System.out.println("Sleep was interrupted");
} catch(Exception exc) {
exc.printStackTrace();
}
sleep() throws InterruptedException when it is interrupted. So "Sleep was interrupted" will be printed on interrupt() while "After the sleep statement" is called only if sleep() managed to sleep configured 20 seconds.
If you don't care whether sleep() returned normally or thrown and just continue your work, wrap it with empty try-catch:
public void interruptibleSleep(long millis) {
try {
Thread.sleep(millis);
} catch(InterruptedException exc) {}
}
and then instead of Thread.sleep(20000) call interruptibleSleep(20000):
interruptibleSleep(20000);
System.out.println("After the sleep statement");
I think you're confused. Here's what happens
public void run() {
// This executes as soon as the thread is run
try {
// We decide to sleep for UPTO 20 seconds
Thread.sleep(20000);
// Code here executes ONLY if we managed to sleep for 20 seconds without
// interruption
} catch(InterruptedException exc) {
// Code here executes ONLY if we were interrupted
} catch(Exception exc) {
// This shouldn't ever execute in theory
}
// Code here ALWAYS executes after the sleeping (and ONE of the two blocks)
// whether or not it was interrupted.
}
There is a very well phrased paragraph at The Java Tutorials
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. This is the usage emphasized in this lesson.
Stopping and staring threads reliably is an important part of designing concurrent applications. And even though you could repurpose interrupts to do whatever you want, your code will be more reliable and easier to maintain for others if you leave interrupt for it's most common purpose - requesting that the thread exit. This is something you will probably want to do if the user decides to shutdown the app before the 20 second timeout is finished.
So how to solve the original problem - allowing one thread to indicate to another that it is time to get to work. The class below shows how a CountDownLatch might be used to solve this problem.
The new Foo:
class Foo extends Thread
{
CountDownLatch latch = new CountDownLatch(1);
#Override
public void run()
{
try
{
boolean early = latch.await(20, TimeUnit.SECONDS);
System.out.println("Doing work " + (early ? "right away" : "after delay"));
// do real work here...
}
catch (InterruptedException e)
{
System.out.println("Interrupt detected. Exiting thread...");
}
}
public void goAhead()
{
latch.countDown();
}
}
We get rid of the "Sleep" and replace it with a call to the await method of the latch object. To make foo do work, invoke:
foo.goAhead(); // prints out "Doing work right away"
This causes the latch to countdown. The call to "await" will immediately exit without throwing an exception and returning true.
To shut down foo, use:
foo.interrupt(); // prints out "Interrupt detected..."
This will cause await to throw an InterruptedException just like sleep.
Or do nothing. The call to await times out after 20 seconds, does not throw an exception and returns false. Foo prints out "Doing work after delay"
One long term advantage of this design as that while you are "doing work" you may need to call other blocking methods. Interrupt can still be used to interrupt any of them and help you on your way to shutting down the thread reliably in response to unexpected events.

Stopping thread Immediately

I want to stop a running thread immediately. Here is my code:
Class A :
public class A() {
public void methodA() {
For (int n=0;n<100;n++) {
//Do something recursive
}
//Another for-loop here
//A resursive method here
//Another for-loop here
finishingMethod();
}
}
Class B:
public class B() {
public void runEverything() {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
A a = new A();
a.methodA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
My problem is that i need to be able to stop the thread in Class B even before the thread is finished. I've tried interrupt() method, but that doesn't stop my thread. I've also heard about using shared variable as a signal to stop my thread, but I think with long recursive and for-loop in my process, shared-variable will not be effective.
Any idea ?
Thanks in advance.
Thread.interrupt will not stop your thread (unless it is in the sleep, in which case the InterruptedException will be thrown). Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn't cause a thread to stop immediately.
When you have long looping operations, using a flag to check if the thread has been cancelled is a standard approach. Your methodA can be modified to add that flag, so something like:
// this is a new instance variable in `A`
private volatile boolean cancelled = false;
// this is part of your methodA
for (int n=0;n<100;n++) {
if ( cancelled ) {
return; // or handle this however you want
}
}
// each of your other loops should work the same way
Then a cancel method can be added to set that flag
public void cancel() {
cancelled = true;
}
Then if someone calls runEverything on B, B can then just call cancel on A (you will have to extract the A variable so B has a reference to it even after runEverything is called.
I think you should persevere with using Thread.interrupt(). But what you need to do to make it work is to change the methodA code to do something like this:
public void methodA() throws InterruptedException {
for (int n=0; n < 100; n++) {
if (Thread.interrupted) {
throw new InterruptedException();
}
//Do something recursive
}
// and so on.
}
This is equivalent declaring and using your own "kill switch" variable, except that:
many synchronization APIs, and some I/O APIs pay attention to the interrupted state, and
a well-behaved 3rd-party library will pay attention to the interrupted state.
Now it is true that a lot of code out there mishandles InterruptedException; e.g. by squashing it. (The correct way to deal with an InterruptedException is to either to allow it to propagate, or call Thread.interrupt() to set the flag again.) However, the flip side is that that same code would not be aware of your kill switch. So you've got a problem either way.
You can check the status of the run flag as part of the looping or recursion. If there's a kill signal (i.e. run flag is set false), just return (after whatever cleanup you need to do).
There are some other possible approaches:
1) Don't stop it - signal it to stop with the Interrupted flag, set its priority to lowest possible and 'orphan' the thread and any data objects it is working on. If you need the operation that is performed by this thread again, make another one.
2) Null out, corrupt, rename, close or otherwise destroy the data it is working on to force the thread to segfault/AV or except in some other way. The thread can catch the throw and check the Interrupted flag.
No guarantees, sold as seen...
From main thread letsvsay someTask() is called and t1.interrput is being called..
t1.interrupt();
}
private static Runnable someTask(){
return ()->{
while(running){
try {
if(Thread.interrupted()){
throw new InterruptedException( );
}
// System.out.println(i + " the current thread is "+Thread.currentThread().getName());
// Thread.sleep( 2000 );
} catch (Exception e) {
System.out.println(" the thread is interrputed "+Thread.currentThread().getName());
e.printStackTrace();
break;
}
}
o/P:
java.lang.InterruptedException
at com.barcap.test.Threading.interrupt.ThreadT2Interrupt.lambda$someTask$0(ThreadT2Interrupt.java:32)
at java.lang.Thread.run(Thread.java:748)
the thread is interrputed Thread-0
Only t1.interuuption will not be enough .this need check the status of Thread.interrupted() in child thread.

Categories