|
1 | 1 | # CompletableFuture |
2 | 2 |
|
| 3 | +## Blocking |
| 4 | + |
| 5 | +The `get` method blocks the `main` thread until the asynchronous task |
| 6 | +finishes (i.e., until the 3-second sleep ends). |
| 7 | + |
| 8 | +The execution flow is: |
| 9 | + |
| 10 | +``` |
| 11 | +main: "Program started" |
| 12 | +main: calls runAsync → task starts on pool thread |
| 13 | +main: registers whenComplete callback (non-blocking) |
| 14 | +main: calls future.get() → BLOCKS here |
| 15 | + ↓ |
| 16 | + (3 seconds later) |
| 17 | + ↓ |
| 18 | +pool thread: "Task run in: ForkJoinPool..." |
| 19 | +pool thread: "completed" |
| 20 | +main: unblocks, "Program finished" |
| 21 | +``` |
| 22 | + |
| 23 | +```java |
| 24 | +package com.zetcode; |
| 25 | + |
| 26 | +import java.util.concurrent.CompletableFuture; |
| 27 | +import java.util.concurrent.ExecutionException; |
| 28 | +import java.util.concurrent.TimeUnit; |
| 29 | + |
| 30 | +public class RunBlocking { |
| 31 | + |
| 32 | + public static void main(String[] args) |
| 33 | + throws ExecutionException, InterruptedException { |
| 34 | + |
| 35 | + System.out.println("Program started"); |
| 36 | + |
| 37 | + CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { |
| 38 | + |
| 39 | + // Simulate a long-running job |
| 40 | + try { |
| 41 | + TimeUnit.SECONDS.sleep(3); |
| 42 | + } catch (InterruptedException e) { |
| 43 | + throw new IllegalStateException(e); |
| 44 | + } |
| 45 | + |
| 46 | + System.out.printf("Task run in: %s %n", |
| 47 | + Thread.currentThread().getName()); |
| 48 | + }); |
| 49 | + |
| 50 | + future.whenComplete( |
| 51 | + (aVoid, throwable) -> System.out.println("completed")); |
| 52 | + |
| 53 | + future.get(); |
| 54 | + |
| 55 | + System.out.println("Program finished"); |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | + |
| 61 | +## Async addition |
| 62 | + |
| 63 | +```java |
3 | 64 |
|
4 | 65 | ## Async addition |
5 | 66 |
|
|
0 commit comments