Runnable demos for the ankurm.com structured-concurrency-java article: the ExecutorService thread leak and its fix, every built-in Joiner, structure violations, timeouts, a custom Joiner, JSON thread dumps (in-process and jcmd), scoped values, javap diffs of the API on 25, 26, 27 and 28-ea, compiler output for six pieces of 25/26-era code, and the preview class-file trap between 27 and 28. Transcripts in output/. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01CifR2BE7PBvRy5hT8TS9oz
34 lines
1.4 KiB
Java
34 lines
1.4 KiB
Java
import java.util.*;
|
|
import java.util.concurrent.*;
|
|
import java.util.concurrent.StructuredTaskScope.Joiner;
|
|
|
|
/** Five tasks that sleep a random time and fail if they were "too slow". Seeded, so the transcript is repeatable. */
|
|
public class RandomTasks {
|
|
|
|
static class TooSlowException extends Exception {
|
|
TooSlowException(String m) { super(m); }
|
|
}
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
long seed = Long.parseLong(args[0]);
|
|
int threshold = 700;
|
|
Random random = new Random(seed);
|
|
List<Callable<Integer>> tasks = new ArrayList<>();
|
|
for (int i = 0; i < 5; i++) {
|
|
int duration = random.nextInt(1000);
|
|
System.out.println("Duration: " + duration);
|
|
tasks.add(() -> {
|
|
Thread.sleep(duration);
|
|
if (duration > threshold) throw new TooSlowException("Duration " + duration + " greater than threshold " + threshold);
|
|
return duration;
|
|
});
|
|
}
|
|
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) {
|
|
tasks.forEach(scope::fork);
|
|
for (int r : scope.join()) System.out.println("Result: " + r);
|
|
} catch (ExecutionException e) {
|
|
System.out.println("ExecutionException: " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage());
|
|
}
|
|
}
|
|
}
|