As the title says I need a way to stop or interrupt a thread that is blocked waiting on an input from the socket.
I didn't see socket.closeInput()
. However, I did find socket.shutdownInput()
. After calling that (from a different thread that was blocking on the read naturally), my call to bufferedReader.close()
worked fine! (I followed that with calls to printWriter.close()
and socket.close()
.
Try using sock.closeInput() followed by sock.close()
Thread.interrupt() should be the method you're looking for. Be sure that your input-accessing methods also check for InterruptedException and ClosedByInterruptException.
Also look at the corresponding page in the Sun Concurrency Tutorial, as another solution suggests.
Close the socket and the read will be unblocked (will exit with a subclass of IOException). Read reacting to Thread.interrupt is platform dependent (won't work on Solaris 10 for example).
You could simply close() the IO stream/socket from another thread. Then, you could check on a volatile boolean field if the resulting IOException is due the close or something else. I think the close might result in an java.net.SocketException: Socket closed
exception.
Sockets allow to set a timeout via the setSoTimeout()
method. This is the preferred way to stop them blocking.
Otherwise you might want to have a look at the nio
package which allows for non-blocking I/O at the expense of more manual work to manage incoming and outgoing data.