Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly closing Java Process InputStream from getInputStream

I could not find clarification of this in the documentation. But when we have a Process object and call getInputStream(),

Do we get a new stream that we should explicitly close when we are done with it? or do we get the stream that is already there, associated with the Process, that we should not close, but the Process would take care of closing it?

Basically, how should we interact with the stream we get from Process.getInputStream()? close or not to close?

like image 437
Bob Avatar asked Aug 17 '11 18:08

Bob


People also ask

Do I need to close Fileoutputstream?

No. It is not require to close other components.

How do I close InputStream after returning?

What you can do is put a close() method on your class which cleans up any open file handlers, connections, etc., and require the user of the class to be responsible for calling close() .

How do I close InputStream?

close() method closes this stream and releases any system resources associated with the stream.

Should you close InputStream Java?

The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more. I am talking about an InputStream in general.


1 Answers

From reading UNIXProcess.java, this is what happens:

We need to distinguish between two states: either process is still alive, or it is dead.

If the process is alive, by closing OutputStream (goes to stdin of the process), you are telling the process that there is no more input for it. By closing InputStreams (stdout, stderr of the process), process is no longer to write to these (it will get SIGPIPE if it tries).

When process dies, Java will buffer remaining data from stdout/stderr, and close all three streams for you (it is running "process reaper" thread, which is notified on process death). Any attempt to write to OutputStream will fail. Reading from InputStream will return buffered data, if any. Closing any of them has no benefit, but also causes no harm. (Underlying file descriptors are closed by this time).

like image 200
Peter Štibraný Avatar answered Oct 06 '22 12:10

Peter Štibraný