Skip to content

Instantly share code, notes, and snippets.

@hohonuuli
Created October 19, 2022 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hohonuuli/e02b95306f2fe0a2c0393458f0d37f56 to your computer and use it in GitHub Desktop.
Save hohonuuli/e02b95306f2fe0a2c0393458f0d37f56 to your computer and use it in GitHub Desktop.
Loom example for medium article
import jdk.incubator.concurrent.StructuredTaskScope;
// java --enable-preview --source 19 --add-modules jdk.incubator.concurrent Loom.java
public class Loom {
public static void main(String[] args) {
run();
}
public static void run() {
// Simple virtual thread
Thread.startVirtualThread(() -> System.out.println("Hello from virtual thread"));
System.out.println("Hello from main thread");
// Structured concurrency
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var aFuture = scope.fork(() -> {
System.out.println("Hello from structured scope thread 1");
return 1;
});
var bFuture = scope.fork(() -> {
System.out.println("Hello from structured scope thread 2");
return 2;
});
scope.join();
scope.throwIfFailed();
System.out.println("Hello from main thread");
// Integer result = scope.result(e -> new RuntimeException(e));
var a = aFuture.resultNow();
var b = bFuture.resultNow();
System.out.println("a = " + a + ". b = " + b);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment