Java interrupt thread when reading socket [duplicate] Java interrupt thread when reading socket [duplicate] multithreading multithreading

Java interrupt thread when reading socket [duplicate]


It has been answered How to terminate a thread blocking on socket IO operation instantly?

Basically, when you close() the socket, all the associated streams will close, causing all the blocked operations to be unblocked.

Or you can call Thread.interrupt() and it will interrupt the blocking operation causing it to throw the InterruptedException.


The NIO Channels have InterruptableChannels which will be interrupted on blocking operations. You can use NIO with blocking operations so they work much the same as Java IO i.e. you don't have to redevelop your application to use Selectors/Dispatchers etc.