In the context of Java, I create a new thread to read network input when open a GUI window, and when i close the window, i want to release the socket resource and terminate the thread immediately. Now i am using setSoTimeout method, but i don't want to wait the timeout exception. Could anybody give some suggestion? Thanks!
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- Multiple sockets for clients to connect to
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
I know this question is old but as nobody seems to have solved the "mystery" of
Thread.interrupt()
on "modern platforms" I did some research.This is tested on Java 8 on Windows7 (64-bit) (but it will possibly be true for other platforms as well).
Calling
Thread.interrupt()
does not throw anInterruptedIOException
What happens is that theInputStream.read()
method returns with-1
andThread.interrupted()
-flag is set.So the following could be considered a 'corrected' read() throwing
InterruptedIOException
:There are (potentially) three ways to do this:
Calling
Socket.close()
on the socket will close the associatedInputStream
andOutputStream
objects, and cause any threads blocked in Socket or (associated) stream operations to be unblocked. According to the javadoc, operations on the socket itself will throw aSocketException
.Calling
Thread.interrupt()
will (under some circumstances that are not specified) interrupt a blocking I/O operation, causing it to throw anInterruptedIOException
.Note the caveat. Apparently the "interrupt()" approach doesn't work on "most" modern Java platforms. (If someone else had the time and inclination, they could possible investigate the circumstances in which this approach works. However, the mere fact that the behavior is platform specific should be sufficient to say that you should only use it if you only need your application to work on a specific platform. At which point you can easily "try it" for yourself.)
A possible third way to do this is to call
Socket.shutdownInput()
and/orSocket.shutdownOutput()
. The javadocs don't say explicitly what happens with read and/or write operations that are currently blocked, but it is not unreasonable to think that they will unblock and throw an exception. However, if the javadoc doesn't say what happens then the behavior should be assumed to be platform specific.