10

Possible Duplicate:
How to terminate a thread blocking on socket IO operation instantly?

I have client run in thread want to read from socket in Java. But while reading, maybe I want to kill the thread. So I interrupt it, but does socket's reading methods throw InterruptedException? I didn't find.

So, how can I nicely ask thread to die while it's blocking on reading socket?

Thanks

Community
  • 1
  • 1
zaharpopov
  • 16,882
  • 23
  • 75
  • 93
  • Check this : http://stackoverflow.com/questions/5569226/serversocket-thread-close-socket-failed-howto-stop-thread-correctly-java – Saurabh Gokhale May 29 '11 at 04:22
  • [Check this reference](https://stackoverflow.com/questions/54495038/read-from-bufferedreader-for-a-specific-duration/54496477#54496477), it works for **Reader** and **InputStream** – deFreitas Feb 02 '19 at 19:17

2 Answers2

2

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.

Community
  • 1
  • 1
Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
  • 1
    Can I close socket from one thread while another blockin on its "read"? – zaharpopov May 29 '11 at 04:39
  • 8
    I checked this with Java 8 and at least there *no* InterruptedException is thrown. The read method just returns (with -1) and Thread.interrupted() flag is set. – raudi Apr 18 '16 at 14:24
2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130