Structured concurrency
Manage concurrent task lifetimes as a single unit of work.
Porównanie kodu
✕ Java 8
ExecutorService exec =
Executors.newFixedThreadPool(2);
Future<User> u = exec.submit(this::fetchUser);
Future<Order> o = exec.submit(this::fetchOrder);
try {
return combine(u.get(), o.get());
} finally { exec.shutdown(); }
✓ Java 25 (Preview)
try (var scope = new StructuredTaskScope
.ShutdownOnFailure()) {
var u = scope.fork(this::fetchUser);
var o = scope.fork(this::fetchOrder);
scope.join().throwIfFailed();
return combine(u.get(), o.get());
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
No thread leaks
All forked tasks complete before the scope closes.
Fast failure
ShutdownOnFailure cancels siblings if one fails.
Clear structure
Task lifetime matches the lexical scope in code.
Stare podejście
Manual Thread Lifecycle
Nowoczesne podejście
StructuredTaskScope
Od JDK
25
Poziom trudności
Zaawansowany
Wsparcie JDK
Structured concurrency
Preview
Preview in JDK 25 (fifth preview, JEP 505). Requires --enable-preview.
Jak to działa
Structured concurrency treats a group of concurrent tasks as one operation. If any subtask fails, the others are cancelled. The scope ensures no thread leaks and gives clear parent-child relationships.
Powiązana dokumentacja