0

Possible Duplicate:
Is it possible to read from a Java InputStream with a timeout?

I'm reading from a stream whose origin may hang. How can I "wait" for a BufferedReader.readLine() to return a string for a maximum of a certain time (say five seconds) and continue the program if nothing is read?

Community
  • 1
  • 1
pistacchio
  • 56,889
  • 107
  • 278
  • 420

2 Answers2

1

BufferedReader has ready() method which checks whether the input stream has something ready to read or not. You can use that combined with a timer class or something.

LeleDumbo
  • 9,192
  • 4
  • 24
  • 38
0

It is important to note that this is an IO blocking call. As such, interrupting the thread currently executing this statement will have absolutely no effect.

A clean way of doing this would be to execute this call with an ExecutorService by wrapping it in a Callable implementation. By calling the get(timeout) method on the returned future, you can both control the timeout manually as well as handle interruptions gracefully.

If this thread is interrupted, you will want to close the underlying resource so that the call itself will actually return and you don't leak threads. Something like myInputStream.close().

allingeek
  • 1,378
  • 8
  • 16