Skip to content

Instantly share code, notes, and snippets.

@orende
Last active September 20, 2023 18:45
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 orende/2b385c4ed0559474634c54cb592d85e5 to your computer and use it in GitHub Desktop.
Save orende/2b385c4ed0559474634c54cb592d85e5 to your computer and use it in GitHub Desktop.
All the major features from JDK 21 in one file
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.function.Supplier;
import java.util.stream.IntStream;
public class Main {
record Coordinate(int x, int y, int z) {}
private static void stringTemplates() {
var name = "Ola";
var age = 100;
var str = STR."""
Hejsan! Your name is \{name} and your are \{age} years old.""";
System.out.println(str);
}
private static void sequencedCollections() {
var myList = new ArrayList<>(List.of(1,2,3,4,5));
System.out.printf("The list %s (reversed: %s) has the last element %s and first element %s.%n",
myList, myList.reversed(), myList.getLast(), myList.getFirst());
myList.addFirst(0);
System.out.printf("List contents: %s%n", myList);
myList.addLast(6);
System.out.printf("List contents: %s%n", myList);
}
private static void virtualThreads() {
System.out.println("Creating and running 10k virtual threads that sleep 1 sec");
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
});
});
}
System.out.println("Done creating and running virtual threads");
}
private static void structuredConcurrency() throws InterruptedException, ExecutionException {
// This structured task scope cancels execution and cleans up if any exceptions are thrown.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Supplier<String> supplierA = scope.fork(() -> {
Thread.sleep(new Random(System.currentTimeMillis()).nextInt(1000, 2000));
return "Result from supplier A";
});
Supplier<String> supplierB = scope.fork(() -> {
Thread.sleep(new Random(System.currentTimeMillis()).nextInt(1000, 2000));
return "Result from supplier B";
});
scope.join().throwIfFailed();
System.out.printf("Result A=%s and B=%s%n", supplierA.get(), supplierB.get());
}
// This structured task scope cancels execution and cleans up as soon as the first task finishes.
List<Callable<String>> tasks = List.of(
() -> {
Thread.sleep(new Random(System.currentTimeMillis()).nextInt(1000, 2000));
return "Result from supplier A";
},
() -> {
Thread.sleep(new Random(System.currentTimeMillis()).nextInt(1000, 2000));
return "Result from supplier B";
}
);
var deadline = Instant.now().plusMillis(1500);
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
for (var task : tasks) {
scope.fork(task);
}
String result = scope.joinUntil(deadline)
.result();
System.out.println("Winner of the race was: " + result);
} catch (TimeoutException e) { // if no tasks finish within the deadline, a timeout exception is raised.
System.out.println("None of the tasks succeeded within the deadline");
}
}
private static void recordPatterns(Object obj) {
switch (obj) {
case Coordinate(int x, int y, _) -> System.out.printf("The x and y coordinates are (%d,%d)%n", x, y);
case null, default -> System.out.println("Error: null or unknown object");
}
}
public static void main(String[] args) throws Exception {
stringTemplates();
sequencedCollections();
recordPatterns(new Coordinate(1,2,3));
structuredConcurrency();
virtualThreads();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment