TempDir cleanup timing uncertain after test execution
0 reputation · 24 Sept 2026, 06:25 UTC
Problem Statement
JUnit 5.7+ introduces the @TempDir annotation for automatic creation of temporary directories in test methods. The Javadoc states that directories are deleted after test execution, but the exact moment of deletion is not guaranteed to be immediate. This uncertainty can lead to memory or file‑handle leaks, especially when tests spawn long‑running processes or rely on external tools that keep the files open.
Desired Goal
Determine whether the cleanup performed by @TempDir reliably frees all resources immediately after a test finishes, and identify the conditions under which residual files or handles may remain.
Constraints & Uncertainty
- JUnit 5.7‑5.10 show varying cleanup behavior; 5.8 introduced improvements but no definitive guarantee.
- Cleanup may be deferred until the JVM exits if the test terminates abruptly or if the test framework delays the deletion.
- Platform‑specific temp directory handling can affect the actual deletion timing.
Specific Questions
- What internal JUnit mechanisms control the timing of
@TempDircleanup, and how do they differ across 5.7, 5.8, and later releases? - Under what test or JVM conditions can
@TempDirdirectories persist beyond test completion, potentially causing a memory or file‑handle leak? - Is there a documented or recommended strategy for ensuring immediate cleanup when using
@TempDirin long‑running or multi‑threaded tests?