3

I'm attempting to use Channels.newChannel to wrap an InputStream in order to support interrupts. I've seen conflicting information whether this will work. Including the comment in ReadableByteChannelImpl: // Not really interruptible

In ReadableByteChannelImpl, before making the the blocking call into InputStream.read, AbstractInterruptibleChannel.begin is called which sets up an new Interruptible using sun.misc.SharedSecrets.getJavaLangAccess().blockedOn which will close the wrapped InputStream.

protected final void begin() {
    if (interruptor == null) {
        interruptor = new Interruptible() {
                public void interrupt(Thread target) {
                    synchronized (closeLock) {
                        if (!open)
                            return;
                        open = false;
                        interrupted = target;
                        try {
                            AbstractInterruptibleChannel.this.implCloseChannel();
                        } catch (IOException x) { }
                    }
                }};
    }
    blockedOn(interruptor);
    Thread me = Thread.currentThread();
    if (me.isInterrupted())
        interruptor.interrupt(me);
}

Is it true that if an InputStream will throw an IOException from a blocked read call if it is closed by another thread then ReadableByteChannelImpl will make the wrapped stream interruptible?

Jake Walsh
  • 3,669
  • 5
  • 22
  • 28

1 Answers1

0

Yes, pretty much. The Channels.newChannel() adapter returns a ReadableByteChannelImpl instance unless the stream is a FileInputStream; in that case, it returns a FileChannel, which is also interruptible.

When you do get a ReadableByteChannel, the code you've already examined suggests (and testing confirms) that the underlying InputStream is closed asynchronously by an interrupt() on the thread blocked in a read.

It can depend on the implementation of the InputStream, but implementations included in the core Java runtime will respond to asynchronous closure by throwing an exception in the reading thread. The specific type of exception will vary.

erickson
  • 265,237
  • 58
  • 395
  • 493