How I currently use structured concurrency
Josiah Noel
josiahnoel at gmail.com
Mon May 15 01:00:45 UTC 2023
Heya, not exactly sure if this is the place for this, but thought I'd share
how I'm currently using SC with JDK 20 as a backend dev.
For some non-critical services and some side projects, I've been refactored
from reactive to imperative style. Normally when I use SC it's to
orchestrate multiple API/DB calls and to cancel the tasks if a subtasks
fail. The underlying resources are usually managed by my DI framework
(usually Spring or Avaje), so I don't really have custom logic to clean up
resources.
The only (admittedly minor) complaints I have are the lack of a
runnable fork variation and the annoying checked exceptions. Other than
that, works like a dream.
Below is a ShutdownOnFailure wrapper class I typically use to get around
the 2 complaints.
public class UncheckedShutdownOnFailure implements AutoCloseable {
private final ShutdownOnFailure scope = new ShutdownOnFailure();
public <T> Future<T> fork(Callable<? extends T> task) {
return scope.fork(task);
}
public Future<Object> fork(Runnable task) {
return scope.fork(Executors.callable(task));
}
public void join() {
try {
scope.join().throwIfFailed(this::uncheck);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
private RuntimeException uncheck(Throwable t) {
if (t instanceof final RuntimeException ex) {
return ex;
}
return new IllegalStateException(t);
}
@Override
public void close() {
scope.close();
}
}
--
Cheers, Josiah.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20230514/35693ec2/attachment.htm>
More information about the loom-dev
mailing list