Interrupting a thread that waits on a blocking action? - java

I am running a thread whose main action is to call on a proxy using a blocking function , and wait for it to give it something.
I've used the known pattern of a volatile boolean and the Interruption , but I'm not sure it will work: When I tried to add a catch block for InterruptedException , I get the error:
Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body
So if I'm never going to get anInterruptedException, this means I'll never get out of the blocking action - thus will never stop.
I'm a bit puzzled. Any idea?
public void run() {
Proxy proxy = ProxyFactory.generateProxy();
Source source;
while (!isStopped) {
try {
source = proxy.getPendingSources();
scheduleSource(source);
} catch (Exception e) {
log.error("UnExpected Exception caught while running",e);
}
}
}
public void stop() {
this.isStopped = true;
Thread.currentThread().interrupt();
}

First, you don't really need a separate flag (if you do, use an AtomicBoolean), just check Thread.currentThread().isInterrupted() as your while condition.
Second, your stop method won't work because it won't interrupt the correct thread. If another thread calls stop, the code uses Thread.currentThread() which means the calling thread will be interrupted, not the running one.
Finally, what is the blocking method? Is it scheduleSource()? If that method doesn't throw InterruptedException, you won't be able to catch it.
Try the following:
private final AtomicReference<Thread> currentThread = new AtomicReference<Thread>();
public void run() {
Proxy proxy = ProxyFactory.generateProxy();
Source source;
currentThread.set(Thread.currentThread());
while (!Thread.currentThread().isInterrupted()) {
try {
source = proxy.getPendingSources();
scheduleSource(source);
} catch (Exception e) {
log.error("UnExpected Exception caught while running", e);
}
}
}
public void stop() {
currentThread.get().interrupt();
}

Only a few, well-defined "blocking methods" are interruptible. If a thread is interrupted, a flag is set, but nothing else will happen until the thread reaches one of these well-defined interruption points.
For example, read() and write() calls are interruptible if they are invoked on streams created with a InterruptibleChannel. If a Socket is used as the starting point, calling interrupt() on a Thread blocked in the read has no effect. Note that if a blocking I/O operation is interrupted successfully, the underlying channel is closed.
Another large class of interruptible operations are those thrown by various blocking operations on classes in the java.util.concurrent packages. Of course, the original wait() method is interruptible as well.
Blocking methods can be identified by looking for a throws InterruptedException in their method signatures. They should be well-documented too, to describe any side-effects of interruption.
You can write an interruptible method of your own, but it has to be composed of interruptible lower-level operations itself.

ok, people, don't kill me over this.
I experimented with Thread.stop() for fun, to kick thread out of a blocking action, catch ThreadDeath, keep target thread alive, and move on.
It seems working. The world isn't ending. But I'm just saying. You are responsible for you own doing. Why am I rapping?

You stop method is calling interrupt on the wrong thread. Thread.currentThread() is the thread that is interrupting, not being interrupted.

How are you calling stop from the executing thread?
If you call stop() from another thread, you'll kill it, not the thread running in the try/catch block.

Related

How to avoid from java.nio.channels.ClosedByInterruptException exception during stopping async method

I have some method with render() name which includes very difficult logic and I call it so in my code
Future<File> fileFuture = null;
try {
fileFuture = executor.getThreadPoolExecutor()
.submit(() -> render());
return fileFuture.get(10,TimeUnit.SECONDS);
} catch (TimeoutException e) {
fileFuture.cancel(true);
throw new MyTimeOutException(e);
}
}
render() method opens some I/O resources and when job doesn't finish
till timeout I get such error when timeout happens
java.nio.channels.ClosedByInterruptException
I investigated this problem and found that this happens because
I/O resources stay still open and Thread cannot be terminated
till these resources won't be closed.
But isn't any way for avoiding this exception
I just need to stop my async method when timeout happens.
and I also want add that I use Spring boot if there is any solution with
Spring please tell me
This exception ClosedByInterruptException will be thrown when a thread performing a blocking read or write on an InterruptibleChannel, like a FileChannel, it's interrupted.
When you call fileFuture.cancel(true) the boolean flag indicates that if the task is blocked, the thread may be interrupted. So, as the thread is blocked in a read or write operation it throws a ClosedByInterruptException.
If you want to get rid of the ClosedByInterruptException, then you render() method to tackle with ClosedByInterruptException, to end the process gracefully if it's thrown.

Service interrupts lib, which then throws InterruptException, but doesn't get caught back in service code

In service code, I have a ScheduledTaskExecutor that starts a job, then a second thread that will cancel that first thread by interrupting it. The job checks for interrupts intermittently, and when the job gets one, it will throw an InterruptException; the service has a try/catch around that job and the catch handles that interruption. My problem is, the catch block is never hit. The job is definitely being interrupted, clear from logging statements on the job side, Once it throws the InterruptException, it's lost and the service can't catch it.
I tried changing Thread.interrupted() to Thread.currentThread().interrupted(), but it didn't fix the problem.
Here's the server-side code that waits for the InterruptException from the job. The interrupt signal is sent to thread via another thread that's scheduled to run after a timeout. I've verified the job does get the interrupt signal.
private void run() {
try {
job.run();
} catch (InterruptedException e) {
log.info("Job was interrupted", e);
} finally {
duration.stop();
timer.record(duration);
}
}
Here's how the job checks for interrupts:
public void checkForInterrupt() throws InterruptedException {
if (Thread.currentThread().isInterrupted()) {
logger.info(jobName + " was interrupted");
throw new InterruptedException(jobName + " has been interrupted");
}
}
I'm expecting to see this log line log.info("Job was interrupted", e);
The last thing I hear from the thread is a log statement that confirms it's interrupt flag has been set, after which it throws the InterruptedException.
The job is definitely being interrupted, clear from logging statements on the job side, Once it throws the InterruptException, it's lost and the service can't catch it.
This is a FAQ. Whenever the InterruptedException is thrown, the interrupt flag on the thread is cleared. If you need the thread to be stilled interrupted, you need to re-interrupt it. That is always the correct pattern when catching InterruptedException. The reason for it is that if you are writing some sort of library, you don't want to swallow the interrupt flag which would mean that the caller won't know if a thread was interrupted. Interrupting a thread is designed as a graceful shutdown (as opposed to the deprecated stop() method). So propagating the interrupt thread is always a good pattern.
For example:
...
} catch (InterruptedException e) {
// we always should re-interrupt the thread when we catch InterruptedException
Thread.currentThread().interrupt();
log.info("Job was interrupted", e);
Then when you get back to the caller you can test the interrupt flag:
if (Thread.currentThread().isInterrupted()) {
...
If you want a lot more detailed information about the various methods that throw InterruptedException and the various Thread methods that affect the flag, then see my answer: Methods that Clear the Thread.interrupt() flag
For example, folks should never use Thread.interrupted() because that clears the interrupt flag when it tests it. Your use of Thread.currentThread().isInterrupted() is correct.

Is the Thread really stop when I use new Thread().interrupt();?

I create a Thread like the following code. This Thread will send the POST request.(The code is not yet written , so I didn't post the detail code of Thread )
final Runnable Update_Value = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
**// It will send the POST request to the Server**
}
};
I use the new Thread(Update_Value).start(); to run the Thread.
And I use new Thread(Update_Value).interrupt(); to interrupt the Thread.
1. If I use new Thread(Update_Value).start(); to run the Thread.
2 How to interrupt the Thread when I using new Thread(Update_Value).start(); ?
3 Is the thread close when App close if I didn't close it ?
Sorry about my English...Thanks in advance.
If you use new Thread each time, the two calls create two different threads; they don't act on the same thread.
The interrupt() method does not stop the thread. Rather, it tells the thread to take a look at any interrupt flags that may also have been set, such as a shutdown flag. The thread itself must contain code to check for interrupts and to check for flags such as shutdown flags.
interrupt method is used to send an interrupt signal to a running thread. Calling on a new thread does not make sense.
To properly handle the interrupt signal, your thread code should catch InterruptedException. Something like this:
try {
// do thread task
} catch (InterruptedException e) {
// interrupted: if required do something on interrupt or simply return
return;
}

Java: How do I catch InterruptedException on a thread, when interrupted by another thread?

I'm developing a multithreaded application to make connections to external servers - each on separate threads - and will be blocked until there is input. Each of these extends the Thread class. For the sake of explanation, let's call these "connection threads".
All these connection threads are stored in a concurrent hashmap.
Then, I allow RESTful web services method call to cancel any of the threads. (I'm using Grizzly/Jersey, so each call is a thread on its own.)
I retrieve the specific connection thread (from the hashmap) and call the interrupt() method on it.
So, here is the question, within the connection thread, how do I catch the InterruptedException? (I'd like to do something when the connection thread is stopped by an external RESTful command.)
So, here is the question, within the connection thread, how do I catch
the InterruptedException?
You can not. Since if your thread is blocked on a read I/O operation it can not be interrupted. This is because the interrupt just sets a flag to indicate that the thread has been interrupted. But if your thread has been blocked for I/O it will not see the flag.
The proper way for this is to close the underlying socket (that the thread is blocked to), then catch the exception and propagate it up.
So since your connection threads extend Thread do the following:
#Override
public void interrupt(){
try{
socket.close();
}
finally{
super.interrupt();
}
}
This way it is possible to interrupt a thread blocked on the I/O.
Then in your run method do:
#Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
//Do your work
}
}
So in your case don't try to catch an InterruptedException. You can not interrupt the thread blocked on I/O. Just check if your thread has been interrupted and facilitate the interruption by closing the stream.
When you call Thread.interrupt() on some thread, what happens is that 'interruption' flag is set for that thread. Some methods do check this flag (by Thread.interrupted() or Thread.isInterrupted()) and throw InterruptedException, but usually only methods that can block do that. So there is no guarantee that InterruptedException will ever be thrown in interrupted thread. If you don't call any method that throws InterruptedException, there is no point in catching that exception, since it will not be thrown at all. However you can always check if your thread was interrupted by calling Thread.isInterrupted().
the problem it is with blocking.
Hoverer, try this code, maybe it will help you:
try{
yourObject.read();
}catch(InterruptedException ie){
// interrupted by other thread
}
catch(Exception ex){
// io or some other exception happent
}
your read method, should check if there is available buytes at socket for eg, if there are than read it, othervise go to speel mode. When is sleeping than is available the wake up (InterruptedException) at pur socket read ( whatever read have you) it will be blocked. Some API has a value to max waiting, eg 5 sec 60 sec, if nothing o read than it will be next code executed.
class MyReadingObject
{
public read() throws InterruptedException{
while(shouldIread){
if(socket.available() > 0){
byte[] buff = new byte[socket.avaialble()]
socket.read(buff);
return;
}
else{
Thread.currentThread.sleep(whateverMilliseconds);
}
}
}
}
something like that, but with error handling and some design patterns
Calling interrupt() on a thread doesn't stop it, it just switches on the interrupt flag. It's the responsibility of the code to handle the change in the interrupt status of the thread in consideration and act accordingly. If you are performing a blocking operation in that thread, you are pretty much SOL because your thread is "blocking" on the read. Have a look at the answer which I posted here. So basically, unless you are looping over stuff or periodically checking some flags inside that thread, you have no way of breaking out without closing sockets or stuff like that.
One solution here is to "explicitly" expose the underlying connection object and call close() on it, forcing it to throw some sort of exception, which can be then handled in the threaded code. Something like:
class MyAction extends Thread implements Disposable {
public void doStuff() {
try {
byte[] data = this.connection.readFully();
} catch (InterruptedException e) {
// possibly interrupted by forceful connection close
}
#Override
public void dispose() {
this.connection.close();
}
}
// Elsewhere in code
MyAction action = conMap.get("something");
action.dispose();
Use a try-catch like so:
try {
//code
} catch ( InterruptedException e) {
//interrupted
}
I think that should do the trick, you could also keep a boolean variable on whether to exit, so they would check that variable, if it's true, stop

interrupt() doesn't work

I am trying to terminate the thread in the following code:
public synchronized void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
this.scan();
this.distribute();
this.wait();
}
} catch (InterruptedException e) {}
}
public void cancel() {
this.interrupt();
}
But the thread won't terminate. I used the debugger and found out that after the command this.interrupt(), the thread doesn't get interrupted (I put a watch on the expression this.isInterrupted() and it stays false). Anyone has an idea why this thread won't get interrupted?
Edit:
The problem has been found. Turns out that there were two instances of this thread. I am attaching the problematic code that lead to this:
/* (class Detector extends Thread) */
Detector detector = new Detector(board);
...
Thread tdetector = new Thread(detector); /* WRONG!!! */
...
tdetector.start();
...
According to the docs, if you call interrupt() while the thread is in a wait() state, the interrupt flag will not be set. You should be getting an interrupted exception, which will exit the loop (and the thread).
EDIT
Per my comment and your response, the problem is that you have more than one of these threads running.
You are probably calling cancel on the wrong thread. If you look at it, it cancel() cancels this thread. You probably want to cancel some other thread.
It is also true that your call to isInterrupted() is unnecessary, but that won't cause interrupts to be lost ...
On the other hand, if the cancel method is a method of a class that extends Thread, then the this could be the thread that needs cancelling. (The problem for us folks trying to answer is that there is/was insufficient detail in the original question ...)

Categories