The moose likes Beginning Java and the fly likes Buffered Reader Hanging Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Buffered Reader Hanging" Watch "Buffered Reader Hanging" New topic

Buffered Reader Hanging

Cory Hartford
Ranch Hand

Joined: May 16, 2011
Posts: 85

I've been struggling with reading from a dumb device and having the reader hang looking for input; it would result in hanging my program. When the device responded correctly, everything was fine. When the response was wonky and erratic it would hang. I wasn't able to set a standard for bytes received or the like so I was kind of at the device's mercy at what it wanted to send at any given time when it errored. I had to isolate the reader so that in the event that it hung I could handle the error and keep on ' a ' movin. I figured I could write a runnable class, thread the read out and time it. If it hung, I could just .cancel() once the timer (not Java.util Timer) expired. Well, that might of worked, but I tripped over the ready() method for the BufferedReader API; using that as a conditional for opening a read works wonderfully.
I think you can use the available() method for input stream but rather than a boolean I think its an int byte count which would be simple enough to verify before opening a read.
So +1 to the "read the api" crowd. Hopefully this is helpful to others.

‎"The greatest of all weaknesses is the fear of appearing weak." - JB Bossuet
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4087

The problem is that available() is never reliable.

Instead, you might want to consider using an AsynchronousByteChannel. The read operation returns a Future, which you can poll for completion of the read.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: Buffered Reader Hanging
It's not a secret anymore!