A Process object causes 3 operating system file handles to be allocated.
Users of e.g. FileOutputStream are being educated to use constructions like
OutputStream os = new FileOutputStream(...);
try {...} // use os
finally { os.close(); }
It is less obvious that Process also allocates 3 file handles that should be
explicitly closed to avoid hitting operating system limits.
Something like
static void closeStreams(Process p) throws IOException {
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
}
Process p = ...
try {...} // use p
finally { closeStreams(p); }
Perhaps closeStreams should be added to the Process class to enable this idiom?
There is also the issue of making sure that the subprocess terminates when it
is no longer useful. If the subprocess exists for no other purpose than to
communicate with its Java parent, then it should be terminated like this:
Process p = ...
try {...} // use p
finally { closeStreams(p); p.destroy(); }
(unless, of course, the subprocess will notice that its stdio streams have
been closed and automatically die)
See also
4801027: (process spec) Clarify need to invoke Process.destroy