Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java Process.waitFor timeout: terminate and reap the owned child

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

Process.waitFor with a timeout reports whether a child has exited; a false return does not stop the child. The owner must terminate it and account for its streams and descendants.

Operational contract

The method first asks for a normal termination, waits briefly, then requests forceful termination and waits for the child to exit. It restores the interrupt signal if the waiting thread is interrupted. This is a bounded attempt for the direct child only; programs that spawn descendants require a separate process-tree policy, and native termination behavior varies. In the companion command example, output is discarded so a filled pipe cannot keep the child blocked while the parent waits.

Failure case

The depot allows a diagnostic 47 seconds. If it is still alive, timeout is a failure, not a successful zero exit code. The owner terminates the child and records the timeout. If the waiting thread is interrupted, it requests forceful termination before passing the interrupt upward. A production supervisor also checks whether the command launched child processes that outlive this direct handle.

Java code

Java
import java.util.concurrent.TimeUnit;

public class ChildProcessDeadline {
    public static int await(Process child) throws InterruptedException {
        try {
            if (child.waitFor(47, TimeUnit.SECONDS)) return child.exitValue();
            child.destroy();
            if (!child.waitFor(3, TimeUnit.SECONDS)) {
                child.destroyForcibly();
                child.waitFor();
            }
            throw new IllegalStateException("Child exceeded its deadline");
        } catch (InterruptedException interrupted) {
            child.destroyForcibly();
            Thread.currentThread().interrupt();
            throw interrupted;
        }
    }
}

Performance and ownership cost

Waiting consumes elapsed time rather than CPU in the usual case. One process consumes handles and native memory until exit. A timeout plus cleanup bounds the direct child's lifetime in normal operation, but a forceful kill can still require a reaping wait and cannot guarantee every descendant is gone.

Common Mistakes

  • Do not call a false timed wait a terminated child.
  • Do not report timeout as exit code zero.
  • Do not assume killing one Process handle kills its descendants.

Connected lessons

java
subprocess ownership
process-timeout-and-cleanup
Storage details