The Cause of InterruptedException

From J2me doc we know that:

java.lang.InterruptedException Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it.

The question is if it's posible to get such exception if from one thread i call Thread.Interupt() for other thread where Run() method of other thread waiting on InputStream.Read(char[]buf) ?

13.10.2009 16:25:12
2 ОТВЕТА
РЕШЕНИЕ

The behavior of blocking read in response to thread interrupt is, in fact, undefined. See this long-standing bug for details. The short of it is that sometimes you get EOF, sometimes you get IOException.

5
13.10.2009 16:29:57
Usually you don't get anything.
erickson 13.10.2009 16:44:07
NB The long standing bug was resolved in 2011: "This is no longer an issue in jdk7 because legacy interruptible I/O is disabled by default on Solaris. It was never implemented on Winodws, and not has been implemented on Linux since jdk1.3."
user207421 11.11.2014 02:26:15

Unfortunately, no, the java.io.* classes do not respond to interruptions when they are blocked in read or write methods. Typically what you have to do is close the stream and then handle the IOException that gets thrown. I have this pattern repeated throughout my code:

try {
    for (;;) {
        try {
            inputStream.read(data);

            thread.join();
        }
        catch (IOException exception) {
            // If interrupted this isn't a real I/O error.
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
            else {
                throw exception;
            }
        }
    }
}
catch (InterruptedException exception) {
}

Alternatively the newer java.nio.* classes do handle interruptions better and generate InterruptedIOExceptions when they are interrupted. Note that this exception is derived from IOException and not from InterruptedException so you will probably need two catch clauses to handle either type of exception, one for InterruptedException and one for InterruptedIOException. And you'll want any inner IOException catch clause to ignore InterruptedIOExceptions.

4
23.10.2012 14:14:59
Unfortunately method interrupted() not implemented in j2me
Pirks 13.10.2009 17:08:18
That's true, and neither in Thread.interrupt(). So where is your interrupt going to come from? What motivates the question?
Jonathan Feinberg 13.10.2009 17:44:03