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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With