I do not know whether the following question is a bug or not.
I am using Okhttp version 3.4.2.
I have this thread handling code like this.
public abstract class CustomThread<T> extends Thread {
abstract T execute();
abstract void onResult(T data);
@Override
public void run() {
T object = null;
try {
if (!Thread.currentThread().isInterrupted()) {
object = execute();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (!Thread.currentThread().isInterrupted()) {
onResult(object);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want to call okhttp in abstract T execute () for network requests.
When I invoke CustomThread.interrupt () to interrupt the thread, Okhttp probability will call the following method.
/**
* Throws an {@link InterruptedIOException} if the deadline has been reached or if the current
* thread has been interrupted. This method doesn't detect timeouts; that should be implemented to
* asynchronously abort an in-progress operation.
*/
public void throwIfReached() throws IOException {
if (Thread.interrupted()) {
throw new InterruptedIOException("thread interrupted");
}
if (hasDeadline && deadlineNanoTime - System.nanoTime() <= 0) {
throw new InterruptedIOException("deadline reached");
}
}
Thread.interrupted() will clear the Thread interrupt status. Resulting in CustomThread should not be invoked onResult (object); has been invoked
I would like to know is that your subsequent version can be changed to call Thread.currentThread (). IsInterrupted () to determine whether the thread interrupted?
From the Java documentation:
_鈥淏y convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.鈥漘
Hi.
By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so
But it does not throw InterruptedException, it throws InterruptedIOException, which extends IOException.
Also there's SocketTimeoutException (and anything else) which extends InterruptedIOException.
In result we are left in situation when thread-cancelation and socket-errors finish in same way.
Okio 1.x (Java): https://github.com/square/okio/pull/467
Okio 2.x (Kotlin): https://github.com/square/okio/pull/468
Fixed in the next Okio update.
Most helpful comment
Hi.
But it does not throw InterruptedException, it throws InterruptedIOException, which extends IOException.
Also there's SocketTimeoutException (and anything else) which extends InterruptedIOException.
In result we are left in situation when thread-cancelation and socket-errors finish in same way.