Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I do not close BufferedReader in java? (Stream type reading in multi-threaded program)

I have a multi-threaded program, in which I open a BufferedReader to read content from FIFO(named Pipe) file. As I want to implement stream type of solution to read text from FIFO file continuously, I have created a BufferedReader outside of thread task run, and want to keep that open forever as long as application is running.(No close() on bufferedReader) With the limited(let say 10) threads in ThreadPool will keep look for text in FIFO file and process that text for further. As I am using FIFO it will never reach END OF FILE.

By doing this, For a smaller input file it reads successfully, for a large input file it throws Stream closed IOexception(sporadically). It close automatically, I do not have close() statement. I have a code in place to acquire and close the semaphore lock at the place where i use br.readLine() to handle race condition issue

java.io.IOException: Stream closed
    at java.io.BufferedReader.ensureOpen(BufferedReader.java:122) ~[?:1.8.0_152]
    at java.io.BufferedReader.readLine(BufferedReader.java:317) ~[?:1.8.0_152]
    at java.io.BufferedReader.readLine(BufferedReader.java:389) ~[?:1.8.0_152]

Question:

  1. For this solution I do not want to close the BufferedReader. What are the consequences?
  2. Can I have a bufferedReader which never be closed? if so what steps I should consider in code.
like image 955
Nomad Avatar asked Oct 05 '18 16:10

Nomad


People also ask

What happens if BufferedReader is not closed?

So, if you don't close(), system resources may be still associated with the reader which may cause memory leak.

Is it necessary to close BufferedReader in Java?

When you are finished reading characters from the BufferedReader you should remember to close it. Closing a BufferedReader will also close the Reader instance from which the BufferedReader is reading.

Which of the following method closes the BufferedReader method?

The close() method of BufferedReader class in Java is used to close the stream and release all the system resources associated with the stream operations. Parameters: This method does not accept any parameter. Return value: This method does not return any value.

How do I turn off BufferedReader?

close() method is used to close this BufferedReader stream and free all other system resources linked with this stream. close() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.


1 Answers

BufferedReader is not a thread-safe class, so, we can get an uncountable number of various error on attempt to use the same object of that class from different threads.

like image 149
denis.zhdanov Avatar answered Sep 23 '22 15:09

denis.zhdanov