Skip to content

Commit bf034e7

Browse files
committed
lecture
1 parent 999d6b2 commit bf034e7

File tree

6 files changed

+58
-85
lines changed

6 files changed

+58
-85
lines changed

src/main/java/io/concurrency/chapter11/exam10/CompleteExample.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77

88
public class CompleteExample {
99
public static void main(String[] args) {
10+
1011
MyService myService = new MyService();
11-
CompletableFuture<Integer> future = myService.performAsyncTask();
12+
13+
CompletableFuture<Integer> future = myService.performTask();
1214

1315
future.thenAccept(result -> {
1416
System.out.println("비동기 작업 결과: " + result);
@@ -17,15 +19,14 @@ public static void main(String[] args) {
1719

1820
static class MyService {
1921

20-
public CompletableFuture<Integer> performAsyncTask() {
22+
public CompletableFuture<Integer> performTask() {
2123

2224
ExecutorService executorService = Executors.newSingleThreadExecutor();
23-
2425
CompletableFuture<Integer> future = new CompletableFuture<>();
2526

2627
executorService.submit(() -> {
2728
try {
28-
TimeUnit.SECONDS.sleep(2); // 2초 대기
29+
TimeUnit.SECONDS.sleep(2);
2930
int result = 42;
3031
future.complete(result); // 결과를 완료시킴
3132
} catch (InterruptedException e) {}

src/main/java/io/concurrency/chapter11/exam10/CompleteOnTimeoutExample.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,20 @@
66
public class CompleteOnTimeoutExample {
77
public static void main(String[] args) {
88

9-
CompletableFuture<String> queryFuture = CompletableFuture.supplyAsync(() -> {
9+
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
1010
try {
11-
TimeUnit.SECONDS.sleep(2); // 2초 대기
12-
return "hello world";
11+
TimeUnit.SECONDS.sleep(2);
12+
return "Hello World";
1313
} catch (InterruptedException e) {
1414
throw new RuntimeException(e);
1515
}
1616
});
1717

18-
// completedOnTimeout을 사용하여 지정된 시간 내에 결과가 없으면 기본값을 반환
19-
CompletableFuture<String> resultFuture = queryFuture
20-
.completeOnTimeout("hello java", 1, TimeUnit.SECONDS); // 2초 내에 결과가 없으면 타임 아웃 발생
18+
CompletableFuture<String> cf2 = cf
19+
.completeOnTimeout("Hello Java", 1, TimeUnit.SECONDS);
2120

2221
// 결과 처리
23-
resultFuture.thenAccept(result -> {
22+
cf2.thenAccept(result -> {
2423
System.out.println("결과: " + result);
2524
}).join();
2625
}

src/main/java/io/concurrency/chapter11/exam10/CompletedFutureExample.java

Lines changed: 6 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,15 @@
44

55
public class CompletedFutureExample {
66
public static void main(String[] args) {
7-
CompletableFuture<User> userFuture = getUserInfoAsync(123);
87

9-
// 사용자 정보를 가져온 후 처리
10-
userFuture.thenAccept(user -> {
11-
System.out.println("사용자 정보: " + user);
12-
// 추가로 사용자 정보를 처리 하는 작업 수행 가능
13-
});
14-
15-
}
8+
CompletableFuture<String> cf1 = CompletableFuture.completedFuture("Hello World");
169

17-
// 사용자 정보를 가져 오는 비동기 메서드 (실제 로는 DB 또는 원격 서비스 와 상호 작용)
18-
static CompletableFuture<User> getUserInfoAsync(int userId) {
10+
CompletableFuture<String> cf2 = new CompletableFuture<>();
11+
cf2.complete("Hello World");
1912

20-
// 이미 계산된 사용자 정보를 completedFuture 로 반환
21-
// 비동기 작업이 필요 하지 않은 경우
22-
// 비동기 작업의 결과를 동기적 으로 처리할 때
23-
return CompletableFuture.completedFuture(new User(userId, "John Doe", "[email protected]"));
24-
}
25-
26-
static class User {
27-
private int id;
28-
private String name;
29-
private String email;
30-
31-
public User(int id, String name, String email) {
32-
this.id = id;
33-
this.name = name;
34-
this.email = email;
35-
}
13+
cf1.thenAccept(user -> {
14+
System.out.println("결과: " + user);
15+
});
3616

37-
// Getter 및 toString() 메서드 생략
3817
}
3918
}

src/main/java/io/concurrency/chapter11/exam10/completeExceptionallyExample.java

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,38 +4,32 @@
44

55
public class completeExceptionallyExample {
66
public static void main(String[] args) {
7-
// CompletableFuture 를 생성
8-
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hell world");
9-
networkCall(future);
107

11-
// CompletableFuture 의 결과를 처리 하고 예외 처리
12-
future
13-
.thenApply(result -> {
14-
System.out.println(result);
15-
return result.toUpperCase();
16-
})
17-
.handle((result, throwable) -> {
18-
if (throwable != null) {
19-
System.err.println("네트 워크 호출 에서 예외 발생: " + throwable.getMessage());
20-
} else {
21-
System.out.println("네트 워크 호출 결과: " + result);
22-
}
23-
return null;
24-
});
8+
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello World");
9+
getData(cf1);
10+
11+
CompletableFuture<String> cf2 = cf1
12+
.thenApply(result -> {
13+
System.out.println(result);
14+
return result.toUpperCase();
15+
})
16+
.handle((r, e) -> {
17+
if (e != null) {
18+
System.err.println("Exception: " + e.getMessage());
19+
return "noname";
20+
}
21+
return r;
22+
});
23+
24+
25+
System.out.println("result: " + cf2.join());
2526
}
2627

27-
static void networkCall(CompletableFuture<String> future) {
28+
static void getData(CompletableFuture<String> future) {
2829
try {
29-
// 예외 발생 시 completeExceptionally()를 사용 하여 예외를 설정
30-
throw new NetworkException("네트 워크 호출 실패");
31-
} catch (NetworkException e) {
30+
throw new RuntimeException("error");
31+
} catch (RuntimeException e) {
3232
future.completeExceptionally(e);
3333
}
3434
}
35-
36-
static class NetworkException extends Exception {
37-
public NetworkException(String message) {
38-
super(message);
39-
}
40-
}
4135
}

src/main/java/io/concurrency/chapter11/exam10/isCompletedExceptionallyAndIsCancelledExample.java

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,40 +7,41 @@
77
public class isCompletedExceptionallyAndIsCancelledExample {
88

99
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
10-
CompletableFuture<Integer> firstFuture = CompletableFuture.supplyAsync(() -> {
10+
11+
CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
1112
sleep(1000);
1213
return 10;
1314
});
1415

15-
CompletableFuture<Integer> secondFuture = CompletableFuture.supplyAsync(() -> {
16+
CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> {
1617
sleep(2000);
17-
// return 10;
18-
throw new RuntimeException("두 번째 작업에서 예외 발생");
18+
return 10;
19+
// throw new RuntimeException("두 번째 작업에서 예외 발생");
1920
});
2021

21-
CompletableFuture<Integer> thirdFuture = CompletableFuture.supplyAsync(() -> {
22+
CompletableFuture<Integer> cf3 = CompletableFuture.supplyAsync(() -> {
2223
sleep(1000);
2324
return 20;
2425
});
2526

26-
secondFuture.cancel(true);
27+
// cf2.cancel(true);
2728

28-
CompletableFuture<Integer> combinedFuture = firstFuture.thenCombine(secondFuture.exceptionally(e -> 15), (result1, result2) -> {
29+
CompletableFuture<Integer> combinedFuture = cf1.thenCombine(cf2.exceptionally(e -> 15), (result1, result2) -> {
2930

30-
if (secondFuture.isCancelled()) { // isDone() 과 구분할 수 있다
31+
if (cf2.isCancelled()) { // isDone() 과 구분할 수 있다
3132
return 0;
3233

33-
} else if (secondFuture.isCompletedExceptionally()) { // isDone() 과 구분할 수 있다
34+
} else if (cf2.isCompletedExceptionally()) { // isDone() 과 구분할 수 있다
3435
return result2;
3536

36-
} else if(secondFuture.isDone()){
37+
} else if(cf2.isDone()){
3738
return result1 + result2;
3839
} else{
3940

4041
return -1;
4142
}
4243
})
43-
.thenCombine(thirdFuture, (result2, result3) -> result2 + result3);
44+
.thenCombine(cf3, (result2, result3) -> result2 + result3);
4445

4546
int result = combinedFuture.join(); // 결과 가져오기
4647
System.out.println("최종 결과: " + result);

src/main/java/io/concurrency/chapter11/exam10/isDoneExample.java

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,24 @@
77
public class isDoneExample {
88

99
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
10-
CompletableFuture<Integer> firstFuture = CompletableFuture.supplyAsync(() -> {
10+
11+
CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
1112
try {
1213
Thread.sleep(1000);
13-
return 42;
1414
} catch (InterruptedException e) {
15-
return -1;
1615
}
16+
return 42;
1717
});
1818

19-
CompletableFuture<Integer> secondFuture = firstFuture.thenApplyAsync(result -> {
19+
CompletableFuture<Integer> cf2 = cf1.thenApplyAsync(result -> {
2020
try {
2121
Thread.sleep(1000);
22-
return result * 2;
2322
} catch (InterruptedException e) {
24-
return -1;
2523
}
24+
return result * 2;
2625
});
2726

28-
while (!firstFuture.isDone() || !secondFuture.isDone()) {
27+
while (!cf1.isDone() || !cf2.isDone()) {
2928
System.out.println("작업이 아직 완료되지 않았습니다.");
3029
try {
3130
Thread.sleep(1000);
@@ -35,8 +34,8 @@ public static void main(String[] args) throws InterruptedException, ExecutionExc
3534
}
3635

3736
// 결과 가져오기
38-
int firstResult = firstFuture.get();
39-
int secondResult = secondFuture.get();
37+
int firstResult = cf1.get();
38+
int secondResult = cf2.get();
4039

4140
System.out.println("첫 번째 결과: " + firstResult);
4241
System.out.println("두 번째 결과: " + secondResult);

0 commit comments

Comments
 (0)