okhttp icon indicating copy to clipboard operation
okhttp copied to clipboard

Okio will clear the Thread interrupt status

Open wanpg opened this issue 9 years ago • 4 comments

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?

wanpg avatar Jan 14 '17 07:01 wanpg

From the Java documentation:

“By 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.”

swankjesse avatar Jan 14 '17 12:01 swankjesse

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.

alexoro avatar Sep 26 '17 15:09 alexoro

Okio 1.x (Java): https://github.com/square/okio/pull/467 Okio 2.x (Kotlin): https://github.com/square/okio/pull/468

swankjesse avatar Jul 06 '18 02:07 swankjesse

Fixed in the next Okio update.

swankjesse avatar Jul 06 '18 02:07 swankjesse