views:

1112

answers:

3

As the title says I need a way to stop or interrupt a thread that is blocked wainting on an input from the socket.

+3  A: 

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.

Daniel Schneller
+1. I'd go with running while loop with timeout rather than killing the thread.
eed3si9n
Using NIO might be too complex for a simple Cancel operation. Btw,"Using Exceptions for program flow control is very bad style" unfortunately, setSoTimeout will result in SocketTimeoutException.
kd304
+4  A: 

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.

Kosi2801
+2  A: 

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.

kd304
Using Exceptions for program flow control is very bad style, especially if it is general purpose ones like "IOException" which could be caused by a variety of things other than timeouts in this case.
Daniel Schneller
You misunderstood me. If you close a socket, the read() throws an IOException - in this case a SocketException. You already have a try-catch for the IOException. If you use Thread.interrupt() it causes an exception to be thrown too. Therefore, you always get some exception. I suggested adding a flag to indicate there was an deliberate cancel/close attempt before the read threw an exception.
kd304