Search code examples
javasocketsnio

Any way of using java.nio.* to interrupt a InputStream#read() without closing socket?


Do you know of a way to interrupt a read from a Java InputStream without closing the associated socket?

Here is the current construction strategy for grabbing a socket input stream and converting to an interruptible DataInputStream:

InputStream interruptibleInputStream = Channels.newInputStream(Channels.newChannel(m_ConnectionData.getSocket().getInputStream()));
DataInputStream myInterruptibleDIS = new DataInputStream(interruptibleInputStream);

This makes use of a ReadableByteChannel which offers a read(ByteBuffer) method with support for a ClosedByInterruptException throwable.

The problem is that calling an interrupt on the thread making read() calls on the DataInputStream causes the underlying socket to be closed.

For my context I need the socket to remain open; the read call is awaiting user input which isn't coming, so I'm using the interrupt to pass control back to a higher component and then ultimately returning to read again.

I'd be very grateful if someone could suggest a way to achieve this using JDK inbuilt classes, or perhaps pointing out that it's not possible with some information.

I understand there are other ways to achieve the same effect, but nevertheless am curious to know whether this approach is feasible.


Solution

  • If you interrupt an InterruptibleChannel during a read, it will be closed and throw a ClosedByInterruptException. If you just want a read timeout, don't use a channel at all, just a regular Socket; call Socket.setSoTimeout() with a shortish timeout, and check the isInterrupted() status of the thread every time the timeout triggers. Better still, review your requirement to interrupt the thread. What's that for?