Java developer reviewing Stream.onClose handlers and try-with-resources cleanup in a code editor

Finishing a Java Stream Does Not Run Its Close Handlers

Fri, Nov 27, 2026

A finite job can return exactly the records you expected and still leave a deliberately owned cleanup obligation unresolved. That is the boundary this laboratory tests. The issue is not whether Java Streams are “leaky” in general. Java SE 21 explicitly notes that most streams backed by collections, arrays, or generators need no special closing, while streams whose source requires resource management must be closed promptly, typically with try-with-resources or an equivalent control structure.

The fixture below starts with an ordinary in-memory sequential stream over the literal IDs A, B, and C, then deliberately attaches one owned synthetic lease through onClose. That artificial obligation lets us ask a narrow production question without opening files, sockets, database cursors, or network connections: did the owner actually invoke the close path, did the modeled release finish successfully, and if processing and cleanup both failed, which exception tree survived? BaseStream.close() is the event that invokes registered close handlers; terminal consumption is a separate event.

The evidence baseline is 2026-11-27: Java SE 21 and JLS 21 are the documentary contracts used here, with the cited pages checked on that date. The ten case outcomes in this article are independently authored expectations. They are EXPECTED / NOT EXECUTED. No observed console transcript, machine version, patch level, operating-system detail, timing, hash, or successful test run is reported. An engineer who executes the exact source must capture those facts from the actual environment and treat an unexecuted case as UNTESTED, never as PASS.

Define the resource contract before accepting terminal results

A reliability review should separate three obligations that are easy to collapse into one. First is the terminal-operation obligation: did the case produce the declared result or the declared processing failure? Second is the ownership obligation: did the code responsible for the resource-bearing stream actually enter its close path? Third is the release obligation: did the resource-specific release operation finish successfully? A green terminal result satisfies only the first question. A callback entry satisfies only the second. In this synthetic fixture, the released flag witnesses the third, but only for the in-memory model.

The lease therefore has two independent cleanup witnesses. releaseAttempts increments immediately when its release method is entered. released changes to true only after the configurable failure point has been passed. A failing release can therefore produce releaseAttempts == 1 and released == false. That distinction matters because AutoCloseable.close() is allowed to throw; the API contract describes automatic invocation under try-with-resources, not a universal guarantee that every underlying release protocol must succeed.

The acceptance vocabulary is intentionally small. ACCEPT_BOUNDARY means the declared processing behavior occurred, the case had a close owner where one was required, the release witness matched the case contract, and failure provenance was preserved. REPAIR_OWNER means the diagnostic evidence shows an owned obligation with no owner-driven close attempt. CLEANUP_FAILURE means the close path was entered but the synthetic release did not complete. HOLD means the evidence is incomplete, inconsistent, taken under the wrong runtime profile, or produced from a changed fixture. A diagnostic negative control such as “full consumption but no close” can match its authored expectation perfectly while remaining unacceptable application behavior.

Consumption and closure must also stay conceptually separate. A stream pipeline consists of a source, intermediate operations, and a terminal operation, but Java’s Stream documentation separately discusses closing resource-bearing streams. Full traversal by forEachOrdered, short-circuit termination by findFirst, and close() are three distinct events. The absence of an exception is not evidence that all three happened. Likewise, a processing exception does not tell you whether cleanup ran afterward.

This article does not revisit count elision, peek, or validation completeness. That is the neighboring concern covered by Java stream traversal and validation evidence. The present fixture uses forEachOrdered only as a stable sequential consumer. It excludes parallel execution, stream reuse, nested flatMap ownership, garbage-collection timing, supplier cancellation, and network behavior. The purpose is to isolate one deliberately transferred close obligation.

The simplest ownership gap is visible in two statements:

stream.forEachOrdered(this::process);
stream.close();

If processing throws, control never reaches the second statement. Adding a catch that ignores the failure merely creates a second defect. The production repair is to put the close obligation in a scope that owns both normal and exceptional exits. Try-with-resources exists for precisely that control-flow shape: a resource declared in its header is closed when the block exits.

Build a finite source with an observable owned lease

The complete laboratory is one Java SE 21 source file named StreamCloseLab.java. It has no third-party dependencies, performs no I/O other than its own diagnostic printing, and uses a fresh state object, lease, and sequential stream for every case. The source factory’s ownership convention is test-specific and explicit: returning the stream transfers responsibility for the attached synthetic lease to the caller. That convention is not a claim that every returned Stream in an API should be owned or closed.

The recorder saves attempted IDs, completed IDs, terminal result, processing outcome, cleanup outcome, handler order, release attempts, release state, and a recursive exception tree before any fixture-only recovery. The processor records an ID in attemptedIds before it can throw at B, and adds the ID to completedIds only after the processing step succeeds. That produces the intentional distinction attempted=[A,B], completed=[A] for the processing-failure cases.

The lease’s fixtureTeardown method is not part of application cleanup. It exists only to reset the synthetic held state after the observation has already been frozen. Its phase is recorded separately, and it never changes the saved Observation. A real adapter qualification would need its own documented release witness. This fixture never infers cleanup from end-of-input, process exit, file deletion, elapsed time, a garbage-collection request, or any other indirect signal. That distinction is the same reason byte-stream completion contracts answer a different question: byte acquisition completeness is not a close-handler witness.

import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;

public final class StreamCloseLab {
    enum ProcessingOutcome { SUCCESS, SHORT_CIRCUIT_SUCCESS, FAILED, NOT_RUN }
    enum CleanupOutcome { NOT_ATTEMPTED, RELEASED, FAILED }
    enum Disposition { ACCEPT_BOUNDARY, REPAIR_OWNER, CLEANUP_FAILURE, HOLD }

    static final class ProcessingFailure extends RuntimeException {
        ProcessingFailure(String message) { super(message); }
    }

    static final class CleanupFailure extends RuntimeException {
        CleanupFailure(String message) { super(message); }
    }

    static final class AuditFailure extends RuntimeException {
        AuditFailure(String message) { super(message); }
    }

    static final class Lease {
        final boolean failRelease;
        int releaseAttempts;
        boolean released;

        Lease(boolean failRelease) {
            this.failRelease = failRelease;
        }

        void release(List<String> handlerEvents) {
            handlerEvents.add("H1");
            releaseAttempts++;
            if (failRelease) {
                throw new CleanupFailure("cleanup-H1");
            }
            released = true;
        }

        void fixtureTeardown(List<String> teardownEvents) {
            if (!released) {
                teardownEvents.add("FIXTURE_FORCE_RELEASE");
                released = true;
            } else {
                teardownEvents.add("FIXTURE_ALREADY_RELEASED");
            }
        }
    }

    static final class CaseState {
        final String id;
        final Lease lease;
        final List<String> attemptedIds = new ArrayList<>();
        final List<String> completedIds = new ArrayList<>();
        final List<String> handlerEvents = new ArrayList<>();
        final List<String> teardownEvents = new ArrayList<>();
        String terminalResult;
        ProcessingOutcome processingOutcome = ProcessingOutcome.NOT_RUN;

        CaseState(String id, boolean failRelease) {
            this.id = id;
            this.lease = new Lease(failRelease);
        }
    }

    record ExpectedCase(
            String id,
            String operation,
            List<String> attempted,
            List<String> completed,
            String terminalResult,
            ProcessingOutcome processingOutcome,
            CleanupOutcome cleanupOutcome,
            List<String> handlerOrder,
            int releaseAttempts,
            boolean released,
            String exceptionTree,
            Disposition applicationDisposition) {}

    record Observation(
            String id,
            List<String> attempted,
            List<String> completed,
            String terminalResult,
            ProcessingOutcome processingOutcome,
            CleanupOutcome cleanupOutcome,
            List<String> handlerOrder,
            int releaseAttempts,
            boolean releasedBeforeTeardown,
            String exceptionTree) {}

    static final List<ExpectedCase> MANIFEST = List.of(
        new ExpectedCase("J01", "forEachOrdered; no close",
            List.of("A", "B", "C"), List.of("A", "B", "C"), "FULL",
            ProcessingOutcome.SUCCESS, CleanupOutcome.NOT_ATTEMPTED,
            List.of(), 0, false, "NONE", Disposition.REPAIR_OWNER),

        new ExpectedCase("J02", "findFirst; no close",
            List.of("A"), List.of("A"), "A",
            ProcessingOutcome.SHORT_CIRCUIT_SUCCESS, CleanupOutcome.NOT_ATTEMPTED,
            List.of(), 0, false, "NONE", Disposition.REPAIR_OWNER),

        new ExpectedCase("J03", "consumer fails at B; no close",
            List.of("A", "B"), List.of("A"), null,
            ProcessingOutcome.FAILED, CleanupOutcome.NOT_ATTEMPTED,
            List.of(), 0, false,
            "ProcessingFailure(process-B){cause=NONE,suppressed=[]}",
            Disposition.REPAIR_OWNER),

        new ExpectedCase("J04", "full consumption, then explicit close",
            List.of("A", "B", "C"), List.of("A", "B", "C"), "FULL",
            ProcessingOutcome.SUCCESS, CleanupOutcome.RELEASED,
            List.of("H1"), 1, true, "NONE", Disposition.ACCEPT_BOUNDARY),

        new ExpectedCase("J05", "explicit close without terminal operation",
            List.of(), List.of(), null,
            ProcessingOutcome.NOT_RUN, CleanupOutcome.RELEASED,
            List.of("H1"), 1, true, "NONE", Disposition.ACCEPT_BOUNDARY),

        new ExpectedCase("J06", "full consumption in try-with-resources",
            List.of("A", "B", "C"), List.of("A", "B", "C"), "FULL",
            ProcessingOutcome.SUCCESS, CleanupOutcome.RELEASED,
            List.of("H1"), 1, true, "NONE", Disposition.ACCEPT_BOUNDARY),

        new ExpectedCase("J07", "findFirst in try-with-resources",
            List.of("A"), List.of("A"), "A",
            ProcessingOutcome.SHORT_CIRCUIT_SUCCESS, CleanupOutcome.RELEASED,
            List.of("H1"), 1, true, "NONE", Disposition.ACCEPT_BOUNDARY),

        new ExpectedCase("J08", "consumer fails; TWR close succeeds",
            List.of("A", "B"), List.of("A"), null,
            ProcessingOutcome.FAILED, CleanupOutcome.RELEASED,
            List.of("H1"), 1, true,
            "ProcessingFailure(process-B){cause=NONE,suppressed=[]}",
            Disposition.ACCEPT_BOUNDARY),

        new ExpectedCase("J09", "explicit close; H1 and H2 fail",
            List.of(), List.of(), null,
            ProcessingOutcome.NOT_RUN, CleanupOutcome.FAILED,
            List.of("H1", "H2"), 1, false,
            "CleanupFailure(cleanup-H1){cause=NONE,suppressed=[" +
            "AuditFailure(audit-H2){cause=NONE,suppressed=[]}]}",
            Disposition.CLEANUP_FAILURE),

        new ExpectedCase("J10", "consumer fails; H1 and H2 fail under TWR",
            List.of("A", "B"), List.of("A"), null,
            ProcessingOutcome.FAILED, CleanupOutcome.FAILED,
            List.of("H1", "H2"), 1, false,
            "ProcessingFailure(process-B){cause=NONE,suppressed=[" +
            "CleanupFailure(cleanup-H1){cause=NONE,suppressed=[" +
            "AuditFailure(audit-H2){cause=NONE,suppressed=[]}]}]}",
            Disposition.CLEANUP_FAILURE)
    );

    static Stream<String> ownedStream(
            CaseState state,
            boolean addFailingAudit) {

        Stream<String> stream = Stream.of("A", "B", "C")
            .onClose(() -> state.lease.release(state.handlerEvents));

        if (addFailingAudit) {
            stream = stream.onClose(() -> {
                state.handlerEvents.add("H2");
                throw new AuditFailure("audit-H2");
            });
        }

        return stream;
    }

    static Function<String, String> processor(
            CaseState state,
            boolean failAtB) {

        return id -> {
            state.attemptedIds.add(id);

            if (failAtB && "B".equals(id)) {
                state.processingOutcome = ProcessingOutcome.FAILED;
                throw new ProcessingFailure("process-B");
            }

            state.completedIds.add(id);
            return id;
        };
    }

    static void consumeFull(
            Stream<String> stream,
            CaseState state,
            boolean failAtB) {

        stream.map(processor(state, failAtB))
            .forEachOrdered(x -> { });

        state.processingOutcome = ProcessingOutcome.SUCCESS;
        state.terminalResult = "FULL";
    }

    static void consumeFirst(
            Stream<String> stream,
            CaseState state) {

        state.terminalResult = stream
            .map(processor(state, false))
            .findFirst()
            .orElseThrow();

        state.processingOutcome =
            ProcessingOutcome.SHORT_CIRCUIT_SUCCESS;
    }

    static Observation runCase(String id) {
        CaseState state;
        Throwable thrown = null;

        switch (id) {
            case "J01" -> {
                state = new CaseState(id, false);
                Stream<String> stream = ownedStream(state, false);
                try {
                    consumeFull(stream, state, false);
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J02" -> {
                state = new CaseState(id, false);
                Stream<String> stream = ownedStream(state, false);
                try {
                    consumeFirst(stream, state);
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J03" -> {
                state = new CaseState(id, false);
                Stream<String> stream = ownedStream(state, false);
                try {
                    consumeFull(stream, state, true);
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J04" -> {
                state = new CaseState(id, false);
                Stream<String> stream = ownedStream(state, false);
                try {
                    consumeFull(stream, state, false);
                    stream.close();
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J05" -> {
                state = new CaseState(id, false);
                Stream<String> stream = ownedStream(state, false);
                try {
                    stream.close();
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J06" -> {
                state = new CaseState(id, false);
                try (Stream<String> stream =
                         ownedStream(state, false)) {
                    consumeFull(stream, state, false);
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J07" -> {
                state = new CaseState(id, false);
                try (Stream<String> stream =
                         ownedStream(state, false)) {
                    consumeFirst(stream, state);
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J08" -> {
                state = new CaseState(id, false);
                try (Stream<String> stream =
                         ownedStream(state, false)) {
                    consumeFull(stream, state, true);
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J09" -> {
                state = new CaseState(id, true);
                Stream<String> stream = ownedStream(state, true);
                try {
                    stream.close();
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            case "J10" -> {
                state = new CaseState(id, true);
                try (Stream<String> stream =
                         ownedStream(state, true)) {
                    consumeFull(stream, state, true);
                } catch (Throwable t) {
                    thrown = t;
                }
            }

            default ->
                throw new IllegalArgumentException(
                    "undeclared case: " + id);
        }

        CleanupOutcome cleanupOutcome =
            state.lease.releaseAttempts == 0
                ? CleanupOutcome.NOT_ATTEMPTED
                : state.lease.released
                    ? CleanupOutcome.RELEASED
                    : CleanupOutcome.FAILED;

        Observation observation = new Observation(
            id,
            List.copyOf(state.attemptedIds),
            List.copyOf(state.completedIds),
            state.terminalResult,
            state.processingOutcome,
            cleanupOutcome,
            List.copyOf(state.handlerEvents),
            state.lease.releaseAttempts,
            state.lease.released,
            renderThrowable(thrown));

        fixtureSnapshotThenTeardown(state, observation);
        return observation;
    }

    static void fixtureSnapshotThenTeardown(
            CaseState state,
            Observation saved) {

        state.lease.fixtureTeardown(state.teardownEvents);

        System.out.println(
            "TEARDOWN " + state.id + " " +
            state.teardownEvents +
            " savedReleased=" +
            saved.releasedBeforeTeardown());
    }

    static String renderThrowable(Throwable t) {
        if (t == null) {
            return "NONE";
        }

        Set<Throwable> seen =
            Collections.newSetFromMap(
                new IdentityHashMap<>());

        return renderThrowable(t, 0, 8, seen);
    }

    static String renderThrowable(
            Throwable t,
            int depth,
            int maxDepth,
            Set<Throwable> seen) {

        if (t == null) {
            return "NONE";
        }

        if (depth > maxDepth) {
            return "DEPTH_LIMIT";
        }

        if (!seen.add(t)) {
            return "CYCLE(" +
                t.getClass().getSimpleName() + ")";
        }

        String cause =
            t.getCause() == null
                ? "NONE"
                : renderThrowable(
                    t.getCause(),
                    depth + 1,
                    maxDepth,
                    seen);

        List<String> suppressed = new ArrayList<>();

        for (Throwable child : t.getSuppressed()) {
            suppressed.add(
                renderThrowable(
                    child,
                    depth + 1,
                    maxDepth,
                    seen));
        }

        return t.getClass().getSimpleName() +
            "(" + t.getMessage() + ")" +
            "{cause=" + cause +
            ",suppressed=" + suppressed + "}";
    }

    static boolean matches(
            ExpectedCase e,
            Observation o) {

        return e.id().equals(o.id())
            && e.attempted().equals(o.attempted())
            && e.completed().equals(o.completed())
            && java.util.Objects.equals(
                e.terminalResult(),
                o.terminalResult())
            && e.processingOutcome() ==
                o.processingOutcome()
            && e.cleanupOutcome() ==
                o.cleanupOutcome()
            && e.handlerOrder().equals(
                o.handlerOrder())
            && e.releaseAttempts() ==
                o.releaseAttempts()
            && e.released() ==
                o.releasedBeforeTeardown()
            && e.exceptionTree().equals(
                o.exceptionTree());
    }

    static void printRuntimeMetadata() {
        System.out.println(
            "java.runtime.version=" +
            System.getProperty("java.runtime.version"));

        System.out.println(
            "java.vendor=" +
            System.getProperty("java.vendor"));

        System.out.println(
            "java.vm.name=" +
            System.getProperty("java.vm.name"));

        System.out.println(
            "os.name=" +
            System.getProperty("os.name"));

        System.out.println(
            "os.version=" +
            System.getProperty("os.version"));

        System.out.println(
            "os.arch=" +
            System.getProperty("os.arch"));
    }

    public static void main(String[] args) {
        printRuntimeMetadata();

        Map<String, Observation> observations =
            new LinkedHashMap<>();

        for (ExpectedCase expected : MANIFEST) {
            Observation observation =
                runCase(expected.id());

            if (observations.put(
                    expected.id(),
                    observation) != null) {

                throw new IllegalStateException(
                    "duplicate observation: " +
                    expected.id());
            }

            boolean diagnosticCaseMatched =
                matches(expected, observation);

            System.out.println(
                "OBS " + observation);

            System.out.println(
                "DECISION id=" + expected.id()
                + " diagnosticCaseMatched=" +
                diagnosticCaseMatched
                + " applicationDisposition=" +
                expected.applicationDisposition());
        }

        if (observations.size() != MANIFEST.size()) {
            throw new IllegalStateException(
                "missing observations");
        }
    }
}

Freeze ten expected cases before observing the implementation

The manifest is authored independently of the observed state. It does not derive expected IDs from the stream source, expected handler order from the event list, or expected exception trees from a caught exception. That independence is essential: a test oracle that copies the implementation’s own output back into its expectation can only confirm self-consistency.

Case

Operation

Authored expectation before teardown

J01

forEachOrdered; no close

Complete A,B,C; zero release attempts; held.

J02

findFirst; no close

Result A; zero release attempts; held.

J03

Consumer fails at B; no close

Attempt A,B; complete A; ProcessingFailure; held.

J04

Full consumption, then explicit close

Complete A,B,C; one release attempt; released.

J05

Explicit close without a terminal operation

No consumed IDs; one release attempt; released.

J06

Full consumption in try-with-resources

Complete A,B,C; release on scope exit.

J07

findFirst in try-with-resources

Result A; release on scope exit.

J08

Consumer fails in try-with-resources; close succeeds

ProcessingFailure stays primary; no suppressed cleanup error; released.

J09

Explicit close; first and second handlers both fail

Handler order H1,H2; CleanupFailure primary, AuditFailure suppressed; lease held.

J10

Consumer fails; same two handlers close under try-with-resources

ProcessingFailure primary; suppressed CleanupFailure itself contains suppressed AuditFailure; lease held.

All ten rows are EXPECTED / NOT EXECUTED. In J09 and J10, H1 is always the release callback and fails before changing released; H2 is always the separate failing audit callback. Their roles are not allowed to drift between cases.

J01 is the simplest negative control. Full consumption can produce attempted=[A,B,C], completed=[A,B,C], and terminal result FULL while leaving releaseAttempts=0 and released=false, because nothing called close(). J02 makes the same ownership defect visible after short-circuiting: findFirst can return A, but that successful result is not a close event. J03 adds abrupt processing. The processor records A, records an attempt for B, then throws ProcessingFailure("process-B") before B enters completedIds. Because this case intentionally has no close owner, its pre-teardown lease remains held.

These three cases should not be described as “passing” merely because the harness reproduced the intended bad pattern. A useful report carries two fields: diagnosticCaseMatched=true means the observation matched the authored negative control; applicationDisposition=REPAIR_OWNER means the pattern is still unacceptable for an owned resource-bearing stream. The catch surrounding each case is an outer recorder. It exists to freeze evidence, not to convert an application failure into success.

An expected evidence row for J03 is therefore illustrative, not a fabricated transcript:

STATUS=EXPECTED/NOT_EXECUTED
id=J03
attempted=[A, B]
completed=[A]
processingOutcome=FAILED
cleanupOutcome=NOT_ATTEMPTED
releaseAttempts=0
releasedBeforeTeardown=false
exceptionTree=ProcessingFailure(process-B){cause=NONE,suppressed=[]}
diagnosticCaseMatched=UNTESTED
applicationDisposition=REPAIR_OWNER

If a real run produces different attempted IDs, handler events, exception structure, or release state, preserve the discrepancy. Do not edit the expectation to make the test green. Record the exact JDK runtime, compiler, vendor, operating system, and source revision, then place the broader conclusion on HOLD until the difference is explained.

Use explicit close and try-with-resources as positive controls

J04 and J05 characterize the close callback independently of traversal. In J04, the case fully consumes A, B, and C and then explicitly calls close(). The release ledger should show one H1 event, one release attempt, and released=true. In J05, the case performs no terminal operation at all; it closes the fresh stream immediately and expects exactly the same release ledger. The comparison demonstrates the narrow point that close-handler execution is tied to the ownership action close(), not to exhaustion of the stream.

That behavior is specified directly by BaseStream: close handlers run when close() is called, they run in registration order, and all registered handlers are attempted even when an earlier one throws. The positive control uses the same Lease implementation as the negative and failing-cleanup cases, so a changed probe cannot explain the difference.

The ownership problem in J04 is not that explicit close is invalid. It is that a success-only statement after processing has an exceptional gap. If consumeFull throws, stream.close() is skipped. J03 already exposes that control-flow shape without adding sleeps, threads, deadlines, or retries. The repair is to make the stream a resource owned by the lexical scope that performs the terminal operation.

J06 does exactly that:

try (Stream<String> stream = ownedStream(state, false)) {
    consumeFull(stream, state, false);
}

J07 keeps the same ownership scope around a short-circuiting terminal operation:

try (Stream<String> stream = ownedStream(state, false)) {
    consumeFirst(stream, state);
}

Try-with-resources closes an initialized resource after the try block on both normal and abrupt completion; the JLS specifies that resource management independently of the stream’s traversal semantics. AutoCloseable likewise states that an object declared in the resource specification is closed automatically on block exit.

That means J07 must be interpreted carefully. findFirst returning A does not itself release the lease. The close attempt occurs because execution leaves the try-with-resources scope. If a helper returns the selected result from inside the block, the language-defined resource closing still occurs as part of leaving the statement; the API contract should nevertheless make ownership transfer explicit so callers know whether a returned stream is owned or borrowed. Do not tell callers to close a borrowed stream whose lifecycle belongs to another component.

J08 is the exceptional positive control. The body attempts A and B, completes A, throws ProcessingFailure, and then the owning scope closes the stream. Because H1 succeeds in this case, the processing exception remains the propagated exception and the synthetic lease is released. Cleanup does not roll back A, and this fixture says nothing about whether a real external side effect is transactional, reversible, idempotent, or safe to retry.

A useful analogy is ownership of an open HTTP streaming response, where a different API exposes a different resource consequence. That page’s evidence concerns connection-pool capacity. It is not authority for Java BaseStream semantics, and this laboratory does not test networking or pool restoration.

For J08, keep two report fields. processingOutcome=FAILED preserves the application failure. cleanupOutcome=RELEASED preserves the successful release. Do not replace the original exception with a summary string or a fresh wrapper that discards its structure. If presentation code must wrap it, preserve the original as cause and retain the original suppressed tree for diagnostics.

Preserve handler order and the recursive exception tree

J09 characterizes the close chain itself. H1 logs H1, increments releaseAttempts, and throws CleanupFailure("cleanup-H1") before setting released=true. H2 then logs H2 and throws AuditFailure("audit-H2"). Java SE 21 specifies that all close handlers are attempted in registration order; when multiple handlers throw, the first exception is relayed and later distinct exceptions are added as suppressed exceptions.

The expected J09 evidence is therefore not just “close failed.” It is handlerOrder=[H1,H2], releaseAttempts=1, released=false, with CleanupFailure as the propagated exception and one suppressed AuditFailure. A handler-entry flag by itself would miss the most important operational fact: the owned release path was invoked but the modeled release never completed. That is CLEANUP_FAILURE, not ACCEPT_BOUNDARY.

J10 combines the already characterized close chain with a processing failure. This is where the BaseStream rule and the JLS try-with-resources rule must remain separate. First, Stream.close() builds its own exception result: H1 throws CleanupFailure, H2 still runs and its AuditFailure becomes suppressed under that CleanupFailure. Second, because the try body was already propagating ProcessingFailure, the JLS rule adds the close failure as a suppressed exception on the earlier body failure.

The required tree is nested, not flat:

ProcessingFailure(process-B)
  suppressed -> CleanupFailure(cleanup-H1)
                  suppressed -> AuditFailure(audit-H2)

Throwable.getSuppressed() exposes suppressed exceptions separately from getCause(), and Java’s Throwable API notes that a throwable may have both a cause and suppressed exceptions. The fixture deliberately uses fresh ordinary RuntimeException instances with default suppression enabled. It does not add experiments for disabled suppression, self-suppression, arbitrary Error subclasses, or cause-chain construction.

The bounded serializer in the source records class, message, cause, and recursively suppressed children without mutating the exception. The depth limit is defensive instrumentation; the fixture’s authored trees are much shallower. Because these three exception classes never set a cause, cause=NONE is expected. A flat log that prints only the top-level exception would lose the cleanup problem in J10. A flat list that prints CleanupFailure and AuditFailure as siblings would also be wrong because it would erase the close chain’s provenance.

This matters operationally because processing failure and cleanup failure are two separate incidents. The service owner may need to address the failed business operation while the resource owner investigates the retained obligation. Whether a real release operation may be retried depends on that adapter’s own contract. This synthetic lease proves no retry safety. Even if a fixture-only recovery later forces released=true, that second action must remain labeled teardown; it cannot rewrite the original J09 or J10 observation as a successful cleanup.

A recursive exception tree should be captured before policy code transforms the error. The original throwable is the best source of provenance. If telemetry requires a structured representation, serialize it alongside the original logging path rather than throwing a new unrelated exception. getSuppressed() is designed for precisely the suppressed-exception relationship produced by try-with-resources and related multi-failure situations.

Capture a reproducible evidence bundle

A production-quality review needs the runtime identity as evidence, not as prose supplied in advance. Before executing the fixture, create a fresh local run directory, copy the exact StreamCloseLab.java into it, and record the source revision or content hash. Then capture compiler and runtime versions separately. javac --release 21 selects the Java SE 21 compilation target; it does not identify the JVM that later executes the class.

A Unix-like procedure can be:

set -eu
run_id="stream-close-$(date -u +%Y%m%dT%H%M%SZ)"
mkdir -p "$run_id/out"
cp StreamCloseLab.java "$run_id/"
cd "$run_id"

java -version >java-version.stderr.txt 2>&1
javac -version >javac-version.stderr.txt 2>&1
uname -a >os.txt 2>&1 || true
sha256sum StreamCloseLab.java >source.sha256.txt

set +e
javac --release 21 -d out StreamCloseLab.java \
  >compile.stdout.txt 2>compile.stderr.txt
compile_status=$?
printf '%s\n' "$compile_status" >compile.exit-status.txt

if [ "$compile_status" -eq 0 ]; then
  java -cp out StreamCloseLab \
    >run.stdout.txt 2>run.stderr.txt
  run_status=$?
  printf '%s\n' "$run_status" >run.exit-status.txt
else
  printf '%s\n' 'NOT_RUN_COMPILE_FAILED' >run.exit-status.txt
fi
set -e

On Windows PowerShell, capture the source hash and OS identity with native commands while keeping the Java compile/run commands unchanged in meaning:

$runId = "stream-close-" + (Get-Date).ToUniversalTime().ToString("yyyyMMddTHHmmssZ")
New-Item -ItemType Directory -Path "$runId\out" -Force | Out-Null
Copy-Item StreamCloseLab.java "$runId\StreamCloseLab.java"
Set-Location $runId

java -version 2> java-version.stderr.txt
javac -version 2> javac-version.stderr.txt
Get-ComputerInfo | Out-File os.txt
Get-FileHash StreamCloseLab.java -Algorithm SHA256 | Out-File source.sha256.txt

javac --release 21 -d out StreamCloseLab.java 1> compile.stdout.txt 2> compile.stderr.txt
$LASTEXITCODE | Out-File compile.exit-status.txt

if ($LASTEXITCODE -eq 0) {
    java -cp out StreamCloseLab 1> run.stdout.txt 2> run.stderr.txt
    $LASTEXITCODE | Out-File run.exit-status.txt
}

The program itself records java.runtime.version, vendor, VM name, os.name, os.version, and os.arch from the running JVM. Preserve those values with stdout rather than copying expected values into the article. For the compiler, preserve the actual javac -version output. For the source, preserve the source file and its hash. For the process, preserve stdout and stderr separately and the exit status. If the runtime behavior disagrees with the documented contract, retain the exact output and environment, then set the conclusion to HOLD until the discrepancy is understood.

The sample size is intentionally finite: exactly one observation for each manifest ID J01 through J10 in a single process, with fresh per-case state. The harness checks that no manifest ID is observed twice and that the number of observations equals the number of declared cases. A stronger qualification could repeat runs, but repetition is not a substitute for case reconciliation. One aggregate “ten cases ran” count cannot tell you whether J03 lost its processing exception or J10 flattened its suppression tree.

The broader engineering habit is similar to future completion versus supplier lifecycle: measure each lifecycle boundary that the contract actually cares about. That neighboring article uses concurrency; this one deliberately does not. Here the boundaries are terminal behavior, close entry, successful release, and exception provenance.

Decide acceptance from the declared obligation and carry it to adapters

The final decision should come from the declared obligation, not from whether the diagnostic fixture “looked green.” The matrix below separates the observed lifecycle facts from the application disposition.

Condition

Diagnostic interpretation

Application disposition

Declared terminal behavior matches; required close attempted; release succeeded; handler and exception evidence complete

Ownership boundary behaved as declared

ACCEPT_BOUNDARY

Terminal behavior may match, but owned stream has zero release attempts where closure is required

Missing cleanup owner or missing owner path

REPAIR_OWNER

Close path entered, but release witness remains false

Cleanup was attempted and failed

CLEANUP_FAILURE

Exception tree loses a processing or cleanup failure

Failure provenance is incomplete

HOLD until instrumentation or propagation is repaired

Missing case row, duplicate row, undeclared case, changed fixture, unknown source hash, wrong runtime profile, or instrumentation failure

Evidence cannot support the conclusion

HOLD

Under the authored manifest, J01-J03 are REPAIR_OWNER. J04-J08 are ACCEPT_BOUNDARY for the specific case contract: J08 still reports failed processing, but the ownership boundary performed the required close and preserved the original failure. J09-J10 are CLEANUP_FAILURE because the release attempt did not complete. None of those labels means the business operation was successful in every case; they classify the lifecycle boundary under review.

Ownership roles should also be explicit. The API author defines whether a returned resource-bearing stream transfers ownership. The caller closes streams it owns. The adapter owner defines what “release succeeded” means for the real resource. QA owns the manifest independence, environment capture, and reconciliation between expected and observed evidence. The service owner handles retained obligations and production escalation. The lesson from observing failures in Java periodic tasks is relevant only as an observability boundary: an operationally important exception must remain visible. Its executor semantics are outside this experiment.

Requalification is warranted when the stream-producing factory changes, the close-handler chain changes, the ownership convention changes, the runtime profile changes materially, or exception translation policy changes. A change to the adapter-specific release witness also deserves review because a callback flag is not enough to prove an external resource completed its protocol. Closing a stream does not roll back completed processing; the A recorded as completed before B fails remains completed in this in-memory ledger.

To move from this synthetic probe to a real resource adapter, preserve the same contract shape but replace the release witness with evidence specific to that resource. A file-oriented adapter may have a documented close state; a cursor or client may expose a documented lifecycle method or externally observable capacity. The qualification must cite that adapter’s contract and define what counts as release success before testing. Do not infer descriptor counts, pool restoration, server cancellation, remote transaction outcome, or retry safety from this Java-only fixture.

The scope limits are deliberate. This article does not test parallel pipelines, nested stream ownership, asynchronous cleanup, abrupt JVM or process termination, external side effects, supplier cancellation, network-pool tuning, InputStream EOF, or garbage-collection timing. It also does not test repeated close() calls or make claims about idempotence across arbitrary AutoCloseable implementations. The in-memory fixture is evidence about Java control flow around one owned Stream.onClose obligation, nothing more.

When evidence is missing, choose HOLD. When the stream has an owned obligation but no close owner, choose REPAIR_OWNER. When close runs but release fails, choose CLEANUP_FAILURE. Choose ACCEPT_BOUNDARY only when the declared terminal behavior, required ownership action, release condition, handler evidence, and exception provenance all reconcile. That decision rule prevents a correct return value from masking an unfulfilled cleanup obligation.

For release review, retain the four-column ownership ledger alongside the case evidence: producer/factory, transferred owner, close mechanism, and release witness. The ledger is deliberately simpler than the case manifest. Its job is to make an ownership handoff reviewable before a failure occurs. If the factory returns a stream whose close handler owns a lease, the transfer must say so. If the caller only borrows the stream, the producer must retain the close obligation. If nobody can state which side owns the close, that ambiguity is itself a HOLD condition until the contract is repaired. The ledger should name the adapter-specific witness separately from close() entry so operations staff do not mistake an attempted cleanup for a completed release.

Develop backend lifecycle skills with Refonte Learning

The engineering skill here is broader than one Java API: connect return values to ownership scopes, and connect both to evidence that survives failure. Refonte Learning’s Backend Developer Program is listed as a three-month program with a stated dedication of 10–12 hours per week. Its published curriculum names Node.js and Express, MongoDB and SQL, RESTful APIs and microservices, authentication and authorization, testing and debugging backend services, Docker and cloud deployment, and a capstone project; the page also lists basic programming concepts as a requirement and separately states an admission prerequisite of working toward a bachelor’s or higher-level degree.

For engineers who want structured practice in API, database, testing, and debugging foundations, the Backend Developer Program is a relevant program to review. Its page describes educational mentors and “Seasoned Guidance,” mentions virtual internships in the program summary while separately using the wording “Potential Internship,” and states that a Training Certificate and Certificate of Internship are offered upon successful completion. This article does not claim that Java, Stream.onClose, try-with-resources, or this exact laboratory is part of that curriculum, and it does not imply automatic internship placement, employment, or salary outcomes.