Process onExit Termination Callback

Process.onExit returns a CompletableFuture completed at termination regardless of exit status, so cleanup code can chain instead of blocking on waitFor.

JavaResilience

Code

snippet
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class ExitCallback {

    public static void main(String[] args) throws Exception {
        // 启动一个很快退出的进程:echo 一行
        Process process = new ProcessBuilder("cmd", "/c", "echo", "hi")
                .start();
        if (process.supportsNormalTermination() && System.getProperty("os.name").toLowerCase().contains("win") == false) {
            // 非 Windows 平台改用 sh -c;这里仅演示 onExit 语义
        }

        // onExit:进程终止时完成 future(无论退出状态)
        CompletableFuture<Process> done = process.onExit();
        System.out.println("waiting: isDone=" + done.isDone());

        // 回调在终止时执行:thenRun 拿退出码
        done.thenRun(() ->
                System.out.println("exited with code: " + process.exitValue()));

        // onExit().get() 等价于 waitFor(),但返回 Process 供链式使用
        Process finished = done.get(5, TimeUnit.SECONDS);
        System.out.println("alive: " + finished.isAlive());
        System.out.println("exit:  " + finished.exitValue());
    }
}

How it works

The working surface is the class ExitCallback — everything else is wiring.

Caveats

  • No external surface — every behavior comes from the standard library.

Putting it to use

The demo output is labeled (waiting: isDone=, exited with code:, alive:), so the output doubles as a step-by-step trace of what the file did.

Core lines under the microscope

CompletableFuture<Process> done = process.onExit();

Interactive Tools for This Topic

FAQ

What does Process onExit Termination Callback print when run?
Invoke the file as-is — the `waiting: isDone=`, `exited with code:`, `alive:` prefixes identify which step printed each line.