Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to set a process variable to null in a finally block?

Tags:

java

process

If we have the following code:

Process p = null;
BufferedReader br = null;

try{
    p = Runtime.getRuntime().exec("ps -ef");
    br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    //Do something with br
} catch (Exception e) {
    //Handle catch block
} finally {
    //Do we need to set p = null;
}

Is the p = null required in a finally block or all the associated streams are closed by default?

like image 793
OVB Avatar asked Sep 24 '13 19:09

OVB


2 Answers

There's no need to set the process to null, but it'd be a good idea to explicitly close the BufferedReader in the finally block. Or even better, if using Java 7 or above, consider using try with resources to automatically close the stream.

like image 146
Óscar López Avatar answered Oct 18 '22 02:10

Óscar López


Since you must consume the entire InputStream of the process in order to prevent blocking, once you have done that there will be no great difference whether you explicitly close the reader or not. After the process is dead, the input stream closes and the wrapper readers turn into garbage. They don't engage any other system resources and thus are harmless.

Setting a variable which references the Process instance is of no consequence.

like image 33
Marko Topolnik Avatar answered Oct 18 '22 02:10

Marko Topolnik