Java Structured Concurrency
… continued from the previous post.
Structured Concurrency Preview
I’ve written about structured concurrency, and Java has a preview API1 StructuredTaskScope
2:
|
|
In Java structured concurrency includes cancelation via thread interruption, aborting the unfinished calculations. We
use our old recursive Fibonacci calculation as Slow2
, made cancelable with:
if (Thread.interrupted()) {
throw new InterruptedException();
}
When we run this, it exits after around 100 Milliseconds:
> bazel run //:try6
INFO: Running command line: bazel-bin/try6
*** Finished 129 runs (871 canceled) in 113.267ms - avg 50.995ms, stddev 16.769ms
Which shows us that all virtual threads are started, even though we could only finish 129. Extending the deadline to run to completion gives:
*** Finished 1000 runs (0 canceled) in 373.313ms - avg 172.825ms, stddev 92.234ms
So, Thread.interrupted()
is not free (it’s the blue areas on top), but performant enough to call it often.
Another Example
Mirroring our Go experiments we define a task and a function calling it:
|
|
Running this, we see similar results as in our previous experiment:
> bazel run //:try7
INFO: Running command line: bazel-bin/try7
*** Got "com.fillmore_labs.blog.jvt.TestException: task2 failed" in 520,398ms
So ShutdownOnFailure
closely mimics Go’s errgroup
.
Summary
Java seems to bet on structured concurrency, at least for virtual threads in non-library code. It uses thread
interruption as a means of cancelation, which requires having a handle to the running thread. We might eventually see
support for context propagation, e.g. from OpenTelemetry, for the new constructs. This is conceptually very different
for Go’s context
, which is just hierarchically passed down and cancels tasks, including subtasks, regardless of
whether the canceler is aware of them.
Ron Pressler, Alan Bateman. 2023. Structured Concurrency (Second Preview). In JDK Enhancement Proposals — September 2023 — JEP 462 — <openjdk.org/jeps/462> ↩︎
The code is available on GitHub at github.com/fillmore-labs/blog-javavirtualthreads. ↩︎