This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Buffered Reader Hanging

 
Cory Hartford
Ranch Hand
Posts: 85
Eclipse IDE Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Bartender
Pie
Posts: 5406
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic