Skip to content

Commit ac04004

Browse files
authored
Update README.md
1 parent ccbe5f8 commit ac04004

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

‎async/completablefuture/README.md‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,66 @@
11
# CompletableFuture
22

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
364

465
## Async addition
566

0 commit comments

Comments
 (0)