Timeout Patterns in Java 21: Full Failure vs Partial Results
Note This article uses the Java 21 preview structured concurrency API (StructuredTaskScope, JEP 453). API shape changed in later previews. See Part 9 for Java 21 -> Java 25 migration guidance. C...

Source: DEV Community
Note This article uses the Java 21 preview structured concurrency API (StructuredTaskScope, JEP 453). API shape changed in later previews. See Part 9 for Java 21 -> Java 25 migration guidance. Compile and run with --enable-preview. Originally published on engnotes.dev: Timeout Patterns in Java 21 This is a shortened version with the same core code and takeaways. Timeout handling gets oversimplified pretty often. The real design question is usually not βdid we hit the deadline?β It is βwhat should the response mean once we do?β Some endpoints should fail completely. Others should return what is ready and mark the rest as missing. Structured concurrency helps, but it does not make that decision for you. The Strict Version This is the simple all-or-nothing pattern from the article: public <T> T runInScopeWithTimeout(Callable<T> task, Duration timeout) throws Exception { Instant deadline = Instant.now().plus(timeout); try (var scope = new StructuredTaskScope.ShutdownOnFailur