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

别等时光非礼了梦想. 提交于 2019-12-01 00:48:56

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/8494763/any-way-of-using-java-nio-to-interrupt-a-inputstreamread-without-closing-so

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!