Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Making reference null after closing stream

Tags:

java

Is it a good practice to set stream references to null after closing them? Would this release resources in any way?

Example:

BufferedReader input= new BufferedReader(new FileReader("myfile.txt"));

// code

input.close();
input = null;

// possible more code
like image 585
Hei Avatar asked Mar 22 '10 19:03

Hei


People also ask

What happens if you dont close InputStream Java?

resource-leak is probably more of a concern here. Handling inputstream requires OS to use its resources and if you don't free it up once you use it, you will eventually run out of resources.

Can you set an object to null?

In order to set object values to null, you need to get all the keys from the object and need to set null. You can use for loop or forEach() loop.


2 Answers

No, it's bad practice. IMO, you should even consider making the variable final.

Resource handling should be handled in the standard acquire(); try { use(); } finally { release(); } manner. In this case:

final Reader rawIn = new FileReader("myfile.txt"); // Character encoding??
try {
    BufferedReader in = new BufferedReader(rawIn);

    // code

} finally {
    rawIn.close();
}

Actually this code picks up whatever character encoding is set as default. I suggest being explicit with either a particular hard-coded charset or Parameterise from Above.

final InputStream rawIn = new FileInputStream("myfile.txt");
try {
    BufferedReader in = new BufferedReader(
        new InputStreamReader(rawIn, "UTF-8")
    );

    // code

} finally {
    rawIn.close();
}

You should not create the wrapper streams/readers outside of the try block (and before the resource assignment) because they might throw. Similarly their close might throw (this was actually a bug in BufferedOutputStream which could throw on flush). Some input streams may have other resources so you need two try { ... finally { x.close(); }s.

For output, you generally should flush in the normal course of events. But generally don't in exceptional cases. Indeed close usually does a flush, therefore you should not close them in the exceptional case. If decorators both flush and have resources, then you'll have to grin and bare it.

There are highly infrequent occasions when nulling out is a good idea. For instance if a variable is the sole reference to a large object and you are going to create a new large object to assign to it, it may be best to clear the reference to allow the old to be reclaimed before allocating the new.

like image 190
Tom Hawtin - tackline Avatar answered Sep 21 '22 00:09

Tom Hawtin - tackline


Not needed. Just input.close() is enough. Remember its always wise to do this inside a finally block. And before calling close() its better to do a null check like this

finally{
  if(input!=null){
    input.close();
  }
}
like image 23
bragboy Avatar answered Sep 19 '22 00:09

bragboy