On Mon, 27 Oct 2025 18:42:32 GMT, Roger Riggs <[email protected]> wrote:
>> The teardown of a Process launched by `ProcessBuilder` includes the closing
>> of streams and ensuring the termination of the process is the responsibility
>> of the caller. The `Process.close()` method provides a clear and obvious way
>> to ensure all the streams are closed and the process terminated.
>>
>> The try-with-resources statement is frequently used to open streams and
>> ensure they are closed on exiting the block. By implementing
>> `AutoClosable.close()` the completeness of closing the streams and process
>> termination can be done by try-with-resources.
>>
>> The actions of the `close()` method are to close each stream and destroy the
>> process if it has not terminated.
>
> Roger Riggs has updated the pull request incrementally with one additional
> commit since the last revision:
>
> Add \@implNote to recommend overriding close and calling `super.close()`.
Roger, I'm thinking about that example in `close()`. It would be a ready-to-run
program, if not for the method name: `example`. Since the text already says
that it's an example, we could rename the method to `main` without loss of
information.
This way the example could be pasted into a file and run, thanks to JEP 512:
Compact Source Files and Instance Main Methods. Note, I used `var` for the
reader and writer to get rid of imports from `java.io`, but it's not essential
as a decent IDE would insert them on paste.
void main() {
try (Process p = new ProcessBuilder("cat").start();
var writer = p.outputWriter();
var reader = p.inputReader()) {
writer.write(haiku);
writer.close();
// Read all lines and print each
reader.readAllLines()
.forEach(System.out::println);
var status = p.waitFor();
if (status != 0) {
throw new RuntimeException("unexpected process status: " + status);
}
} catch (Exception e) {
System.out.println("Process failed: " + e);
}
}
String haiku = """
Oh, the sunrise glow;
Paddling with the river flow;
Chilling still, go slow.
""";
-------------
PR Comment: https://git.openjdk.org/jdk/pull/26649#issuecomment-3469753255