Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sockets

nio

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.

like image 629
KomodoDave Avatar asked Dec 13 '11 19:12

KomodoDave


1 Answers

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?

like image 185
user207421 Avatar answered Nov 07 '22 17:11

user207421