Why does Thread.isInterrupted () always return false? - java

I found the method of JavaDoc:
Returns:
true if this thread has been interrupted; false otherwise.
I think something wrong with my understanding of the method. Further, I may misunderstand the concept ‘interrupt’ in Thread.
Any explanation is welcome! Thank you!
Code snippet:
In thread definition:
public void run() {
try {
//Do something
} catch (InterruptedException e) {
System.out.println(isInterrupted());//Always false
return;
}
}
invoke:
theThread.interrupt();

This behaviour is typically documented in methods that throw that exception. For example, the javadoc for Object.wait() says:
"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."
Indeed, the javadoc for the exception itself says this:
"Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:
if (Thread.interrupted()) // Clears interrupted status!
throw new InterruptedException();
Note how they emphasize that the flag should be cleared before the exception is thrown.
Why was it designed to work like this? You'd have to ask the designers, but I expect they figured that an exception handler should handle the situation, and that there should therefore be no need for the flag to still be set at that point. (If the handler doesn't fully handle the situation it can either rethrow the exception, or call Thread.getCurrentThread.interrupt() to set the flag again.)

Once the exception is thrown, the thread is no longer in an interrupted state.

Adding to cdhowie's answer, one standard pattern is to let the Thread handle interruption. This is useful with Executors, when the running code doesn't "own" the Thread and should not get in the way of interruption (unless you really know what you're doing)
public void run() {
try {
//Do something
} catch (InterruptedException e) {
// Do whatever local clean up you need to
...
// Then let the owning Thread know it's been interrupted, so it too can clean up
Thread.currentThread().interrupt(); //
}
}

You would check isInterrupted() in your own code, for example from a loop. If the thread has been interrupted you can then throw InterruptedException to stop executing.
In your example if you caught InterruptedException you can be sure that it was interrupted and you don't have to check that method.

Related

How to fix Sonar issue "Remove this call to "wait" or move it into a "while" loop"?

I am received a request to fix sonar issues in a legacy project, there is a code segment like this, every call to this function will be paused for 50ms:
synchronized(monitor) {
[...]
try {
[...]
Thread.sleep(config.getWaitTime()); // return 50
} catch (SomeException e) {
log.error(e.getMessage(), e);
}
[...]
}
First, sonar asked me to change Thread.sleep() to wait() so I change the try block to to:
try {
[..]
monitor.wait(config.getWaitTime());
} catch (SomeException e) {
log.error(e.getMessage(), e);
}
Then, another issue appear : Remove this call to "wait" or move it into a "while" loop , I do not have much experience with multithreading, so I'm not sure my fix is correct:
boolean wait = true;
while (wait) {
wait = false;
monitor.wait(config.getWaitTime());
}
Is the above solution correct? If not, what should I do?
From the Object#wait() Java doc
A thread can also wake up without being notified, interrupted, or
timing out, a so-called spurious wakeup. While this will rarely occur
in practice, applications must guard against it by testing for the
condition that should have caused the thread to be awakened, and
continuing to wait if the condition is not satisfied. In other words,
waits should always occur in loops, like this one:
synchronized (obj) {
while (<condition does not hold>)
obj.wait(timeout);
... // Perform action appropriate to condition
}
Your loop doesn't look good, it should be something like:
while (wait) {
monitor.wait(config.getWaitTime());
}
The wait variable must be set from elsewhere, when the wait condition is no longer needed.
Here the while appears helpless :
boolean wait = true;
while (wait) {
wait = false;
monitor.wait(config.getWaitTime());
}
The while statement around the wait() statement is designed to check that the wait() be re-invoked if the logical/function condition in the while is true but in your case it is never as you assign wait to false as first statement of the while body.
The while is so helpless.
Here is the Object.wait(long) javadoc associated to :
A thread can also wake up without being notified, interrupted, or
timing out, a so-called spurious wakeup. While this will rarely occur
in practice, applications must guard against it by testing for the
condition that should have caused the thread to be awakened, and
continuing to wait if the condition is not satisfied.
As often I am not convinced at all of Sonar advises....
You could use a timer to check that the required time was elapsed in the while. But ugg.
I advise you to keep the Thread way that suits to your requirement.
Or if you want to make the tool API add helpless code. Of course I am joking : don't do that !
sonar asked me to change Thread.sleep() to wait()
Just ignore sonar here. It is false positive alarm.

Guarded blocks -- notifyAll() vs interrupt()

This Q looks for verification and/or comments/opinions the following:
The example on Guarded Blocks is as follows:
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!");
}
The other end of this code-- the one setting joy properly is something like this:
public void setJoy2(TheClass t) {
synchronized (t) {
t.joy = true;
t.notifyAll();
}
}
The above does the "signaling" on joy by the use of notify().
An alternative is managing this "signalling" by interrupt():
public void guardedJoy2() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
synchronized(this) {
try {
wait();
} catch (InterruptedException e) {}
}
}
System.out.println("Joy and efficiency have been achieved!");
}
and the one setting joy and letting the thread waiting for it is:
public void setJoy2(TheClass t) {
t.joy = true;
t.interrupt();
}
I'm looking to make a comparison between the two-- setJoy() and setJoy2().
First of all, guardedJoy2() above can "hear" both setJoy() and setJoy2() properly-- can see when joy is set and act the way it is expected to(?)
How does guardedJoy2() compare to guardedJoy()?
It achieves does the same thing as guardedJoy()-- i might be missing something, but i'm not seeing a difference in the outcome. The only difference is that guardedJoy2() released the lock of this from within the loop, and someone else acquire it before the method terminates for some unexpected results. Setting that aside (i.e., assuming that this is the only place where the use of joy and its side effects appear in the code), there's not difference between guardedJoy() and guardedJoy2()(?)
guardedJoy2() responds to both setJoy() and setJoy2().
It can "hear" from setJoy() when it is done, re-acquires its lock and go from there.
And, it can "hear" from setJoy2()-- by receiving the interrupt and thus throwing InterruptedException to get out of wait(), that's also the end of synch'd statement, checks to see in while condition that joy is set and goes from there. If the interrupt was from "someone" else and not from the one setting joy, gets into the loop again the same way till joy is set.
When, wait() is invoked and thus the lock of this is released in guardedJoy2(),
some other thread can get in by acquiring this lock and do things that are not supposed to be done till joy is set and guardedJoy2() is supposed to return properly. However, setting this aside (again, assuming this isn't an issue-- the only thing being looked for is seeing that message on the last line of guardedJoy2() on the console.) This-- setJoy2() can be preferable in cases where other things can be done on the object while it's getting its joy set and go from there (in setJoy2(), the thread setting joy doesn't have to have the lock of the object to interrupt it while setJoy() should have that lock to invoke notifyAll() on it).
How does guardedJoy2() & setJoy2() compare to guardedJoy() & setJoy() above?
TIA.
I'm going of the assumption that you meant just notify() in your first setJoy rather than notifyAll().
First, it's important to note that if you're invoking interrupt() on an expression of type TheClass, then TheClass is a subclass of Thread. This goes against a number of -recommendations that state that you should use Runnable instances to encapsulate the logic to be run on a thread rather than subclassing the class Thread. The javadoc of Thread#join(int) also states
It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
This is because some implementations of Java use those methods to handle thread logic behind the scenes. If you do not know that implementation logic and use these methods with Thread instances, you might get undesired behavior.
Then, and this might warrant some profiling, throwing (creating) an exception is an expensive operation, probably more so than removing a Thread from an object's wait set. What's more, exceptions should be used for exceptional conditions, not to guide your application logic.
I was going to say that your second example's synchronization order may be incorrect (assuming joy was not volatile) because the read in the guardedJoy2 loop might not see the write in setJoy2. However, the Java Language Specification states
If thread T1 interrupts thread T2, the interrupt by T1
synchronizes-with any point where any other thread (including T2)
determines that T2 has been interrupted (by having an
InterruptedException thrown or by invoking Thread.interrupted or
Thread.isInterrupted)
So you still have visibility guarantees in place.

A Mutex for inter-threading usages in Java?

I want a Mutex in Java which let me to wait on it in a thread and release it in another thread. I know that I can use a Semaphore with capacity of 1 but the problem is that the "acquire()" method throws "InterruptedException". Is there any special synchronization way for this purpose in Java?
Luckily, Semaphore provides this method for you :)
public void acquireUninterruptibly()
Acquires a permit from this semaphore, blocking until one is
available. Acquires a permit, if one is available and returns
immediately, reducing the number of available permits by one.
If no permit is available then the current thread becomes disabled for
thread scheduling purposes and lies dormant until some other thread
invokes the release() method for this semaphore and the current thread
is next to be assigned a permit.
If the current thread is interrupted while waiting for a permit then
it will continue to wait, but the time at which the thread is assigned
a permit may change compared to the time it would have received the
permit had no interruption occurred. When the thread does return from
this method its interrupt status will be set.
InterruptedException is not an issue, just wrap it in a loop:
while(true) {
try {
semaphore.acquire();
break;
} catch(InterruptedException e) {
//swallow, continue;
}
}
However this code is not very safe and elegant, but will work providing that you "want to make sure you can acquire a permit!"
if you have a code in which a thread is going to wait then you will definitely have to handle interrupted exception unless you are using synchronized block. Also, What is the problem with interrupted exception?
ThreadA
volatile boolean waitCondition = true
synchronized(lockObject) {
while (waitContidion) {
lockObject.wait();
}
}
ThreadB
synchronized(lockObject) {
waitCondition = false;
lockObject.notifyAll();
}
or use Condition/Signal on Lock instances.
Correct handling of InterruptedException is very important, at least you must set it's interrupted flag with Thread.currentThread().interrupt() method in catch block.

Java - interrupting threads?

I got a question about interrupting threads in Java. Say I have a Runnable:
public MyRunnable implements Runnable {
public void run() {
operationOne();
operationTwo();
operationThree();
}
}
I want to implement something like this:
Thread t = new Thread(new MyRunnable());
t.run();
... // something happens
// we now want to stop Thread t
t.interrupt(); // MyRunnable receives an InterruptedException, right?
... // t is has now been terminated.
How can I implement this in Java? Specifically, how do I catch the InterruptedException in MyRunnable?
I recommend testing for Thread.isInterrupted(). Javadoc here. The idea here is that you are doing some work, most likely in a loop. On every iteration you should check if the interrupted flag is true and stop the work.
while(doingWork && !Thread.isInterrupted() {
// do the work
}
Edit: To be clear, your thread won't receive an InterruptedException if the sub tasks are not blocking or worst, eat that exception. Checking for the flag is the right method but not everybody follows it.
First, the 2nd line of your 2nd block of code should be t.start(), not t.run(). t.run() simply calls your run method in-line.
And yes, MyRunnable.run() must check periodically, while it is running, for Thread.currentThread().isInterrupted(). Since many things you might want to do in a Runnable involve InterruptedExceptions, my advice is to bite the bullet and live with them. Periodically call a utility function
public static void checkForInterrupt() throws InterruptedException {
if (Thread.currentThread().isInterrupted())
throw new InterruptedException();
}
EDIT added
Since I see a comment that the poster has no control over the individual operations, his MyRunnable.run() code should look like
public void run() {
operation1();
checkForInterrupt();
operation2();
checkForInterrupt();
operation3();
}
an InterruptedThreadException is only thrown when the thread is being blocked (wait, sleep, etc.) . Otherwise, you'll have to check Thread.currentThread().isInterrupted().
I think the answers above will pretty much fit your problem. I just want to add something on InterruptedException
Javadoc says:
InterruptedException :Thrown when a thread is waiting, sleeping, or
otherwise paused for a long time and another thread interrupts it
using the interrupt method in class Thread.
This means InterruptedException won't be thrown while running
operationOne();
operationTwo();
operationThree();
unless you are either sleeping, waiting for a lock or paused somewhere in these three methods.
EDIT If the provided code can not be changed as suggested by the nice and useful answers around here then I am afraid you have no way of interrupting your thread. As apposed to other languages such as C# where a thread can be aborted by calling Thread.Abort() Java does not have that possibility. See this link to know more about the exact reasons.
First of all, should be class in there
public class MyRunnable extends Thread {
public void run() {
if(!isInterrupted()){
operationOne();
operationTwo();
operationThree();
}
}
}
Would this work better?

How to "try start" one thread from several other threads, java

I wrote this in my function:
if(myThread.isAlive()) {
} else {
myThread.start();
}
but this is unsafe if many threads call this function the same time. start a running thread throws an exception.
So except putting try-catch around it, do I have other options?
Make this method synchronized. Also, this check (isAlive()) is unsafe because if the thread have been finished you cannot start it again (and isAlive() will return false...)
I would only create the thread when I intend to start it.
What you can do is
synchronized(thread) {
if(thread.getState() == Thread.State.NEW)
thread.start();
}
A thread which has finished will not be alive, but it cannot be retstarted.
Use a syncronized method / block? Use locks?
contrary on what everyone might tell: do not use isAvile() or getState(), both require to execute them into a sync. block along w/ thread.start() and requires that the thread actually uses itself as monitor (de-facto it does so)
instead, just catch the exception (IllegalThreadStateException) of start() and ignore it.
try{
thread.start()
}catch(IllegalThreadStateException _x){
//ignore or log the reason, use getState(), if need be
}

Categories

Resources