I simplified the first example to: void main() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(this::asyncMethod);
future.thenAccept(result -> IO.println(result));
IO.println("Prints first"); // prints before the async result
future.join(); // Wait for future to complete
}
String asyncMethod() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
return "Interrupted";
}
return "Data Fetched";
}
I made the following changes:1. Move the asynchronous function called in the CompletableFuture to its own method 2. Use Java 25 "instance main method" (see JEP 25: https://openjdk.org/jeps/512) 3. Use Java 25 IO.println() to simplify console output 4. Instead of throwing a fatal exception on interruption, return "Interrupted" immediately. 5. Use future.join() so the main method waits for the future to complete and the "Data fetched" output is printed. This program can be run directly from source with `java Example.java`. (If you're using Java 24 or a version of Java 25 prior to EA 22, you need to use `java --enable-preview Example.java`) Here is a modified version of the example that interrupts the thread: void main() {
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture.supplyAsync(this::asyncMethod, executor);
future.thenAccept(result -> IO.println(result));
IO.println("Prints first"); // prints before the async result
executor.shutdownNow();
future.join(); // Wait for future to complete
}
String asyncMethod() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
return "Interrrupted";
}
return "Data Fetched";
}
|