Created
October 19, 2022 04:06
-
-
Save hohonuuli/e02b95306f2fe0a2c0393458f0d37f56 to your computer and use it in GitHub Desktop.
Loom example for medium article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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