How to know if a BufferedReader Stream is closed

Guru picture Guru · Jun 11, 2009 · Viewed 24.3k times · Source

I have two threads in Java.

First thread is closing a bufferedreader (br.close())

When the second thread does a read on the same reader I get an IOException (Stream Closed)

I get this exception even if I use br.ready()

Is there a way to know if the stream is already closed?

Answer

Kathy Van Stone picture Kathy Van Stone · Jun 11, 2009

The method ready() will throw an exception if closed. But even if you added a closed check method, so long as the lock is released between calls (which it is for BufferedReader), the reader might be closed by the time you read it.

I see three options:

  1. Wrap your read call with a try/catch block to handle the closed case.
  2. Create a subclass of BufferedReader that extends close() to set your own variable that can be used to check to see if the reader is closed. This also requires overriding a lot of methods to do whatever the behavior you want with a closed reader if you want it do something beside throw the IOException.
  3. Add a lock of your own and use it to both close the reader (one thread) and check that the buffer is ready and read from it. You can either set a variable directly for the check or just group the ready() and read() calls into the same synchronized block.