Alex Rivera | Logout

How to interrupt BufferedReader's readLine

Asked 2010-08-29T18:03:34.063
50

I am trying to read input from a socket line by line in multiple threads. How can I interrupt readLine() so that I can gracefully stop the thread that it's blocking?

EDIT (bounty): Can this be done without closing the socket?

Edit
Report

1 Answer

-1

A sketch for a solution might be this: NIO provides methods for nonblocking IO, so you have to implement something called Foo that uses nonblocking NIO on the socket end but also provides a InputStream or Reader interface on the other end. If the BufferedReader enters its own read, it will call Foo, which will call Selector.select with read intent. select will either return indicating the presence of more data or it will block until more data is available.

If another thread wants to unblock the reader, it must call Selector.wakeup and the selector can return gracefully by throwing an exception the by BufferedReader.

The socket should be still open after that.

Variation A: call Selector.select(timeout) to do busy polling light.

answered 2011-09-19T21:51:19.267

Your Answer