How I currently use structured concurrency

Ron Pressler ron.pressler at oracle.com
Mon May 15 14:19:27 UTC 2023


I think that combining join with throwIsFailed is perfectly reasonable, and it even was a design we considered but preferred the STS one for pedagogical reasons (we hope to learn if that decision was the right one). But representing cancellation (i.e. interruption) — a perfectly valid behaviour for correct code even in the case of no environmental errors — as an unchecked exception, which usually represents a bug, is not the Java way. Obviously anyone is free to do that, but it’s not something we would consider for a standard API.

— Ron

> On 14 May 2023, at 21:00, Josiah Noel <josiahnoel at gmail.com> wrote:
> 
> 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.



More information about the loom-dev mailing list