Summary
With the introduction of Process.close(), process resource cleanup is now straightforward and complete. By launching a process inside a try-with-resources block, both the process streams and the process itself are properly cleaned up and terminated when exiting the block.
Problem
Previously, callers were responsible for manually closing each process stream and ensuring the process itself was terminated, as there was no unified method to handle all cleanup. While try-with-resources could manage streams, it could not be applied to Process directly since it lacked a close() method and did not implement AutoCloseable.
Solution
The addition of Process.close() and the implementation of the AutoCloseable interface to java.lang.Process allow for consistent and reliable cleanup. Now, try-with-resources can be used with Process to automatically close its streams and terminate the process upon exit. Inside a try-with-resources block, applications have full access to process APIs and streams, enabling them to read, write, close streams, wait for process completion, and check exit status as needed.
Specification
/**
* Close all writer and reader streams and terminate the process.
* The streams are closed immediately and the process is terminated without waiting.
* <p>
* Before calling {@code close} the caller should read the streams for any
* data or text and call {@linkplain #waitFor() waitFor} if the exit value is needed.
* The contents of streams that have not been read fully are lost;
* they are discarded or ignored.
* Streams should be {@code closed} when no longer needed.
* Closing an already closed stream usually has no effect but is specific to the stream.
* IOExceptions that occur when closing streams are ignored.
* <p>
* The process may already have exited or be in the process of exiting;
* if it is {@linkplain #isAlive() alive}, it is {@linkplain #destroy destroyed}.
* IOExceptions that occur when destroying the process are ignored.
* <p>
* Example using try-with-resources writing text to a process, reading back the
* response, and closing the streams and process:
* {@snippet class=ProcessExamples region=example}
*
* @implSpec
* The outputWriter and outputStream to the process are closed.
* The inputReader and inputStream from the process are closed.
* The errorReader and errorStream from the process are closed.
* The process is destroyed.
* @since 26
*/
public void close() {...}
The apidiff and javadoc are attached.
- csr of
-
JDK-8364361 [process] java.lang.Process should implement close and be AutoCloseable
-
- New
-