Java interrupt thread when reading socket [duplicate]
Asked Answered
I

2

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

Inductee answered 29/5, 2011 at 4:19 Comment(2)
Check this : #5569726Ertha
Check this reference, it works for Reader and InputStreamLoginov
M
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.

Menhir answered 29/5, 2011 at 4:24 Comment(2)
Can I close socket from one thread while another blockin on its "read"?Inductee
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.Prieto
C
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.

Calipee answered 29/5, 2011 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.