CompletableFuture
비동기 프로그래밍을 지원하면서, 함수형 프로그래밍 패러다임이 적용된 자바 라이브러리이다.
- 비동기 작업 실행
- 작업 콜백
- 작업들의 조합
- 예외 처리
와 같은기능들을 제공한다.
태스크 실행 (runAsync, supplyAsync)
CompletableFuture.runAsync(() -> {
System.out.println("비동기 작업");
});
CompletableFuture.supplyAsync(() -> {
final String e = "비동기 작업";
System.out.println(e);
return e;
});
- runAsync는 리턴값이 없을 때 사용한다.
- supplyAsync는 리턴값이 있을 때 사용한다.
태스크 콜백 (thenApply, thenAccept, thenRun)
final CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> {
final String e = "비동기 작업";
System.out.println(e);
return e;
});
supplyAsync
.thenApply(e -> {
final String added = " 추가 작업";
System.out.println(e + added);
return e + added;
});
supplyAsync
.thenAccept( e -> {
final String added = " 추가 작업";
System.out.println(e + added);
});
supplyAsync
.thenRun(() -> {
System.out.println("리턴 값을 받지 않는다!");
});
- thenApply: async 실행 결과 값을 받고, 추가 값을 리턴하는 콜백을 실행
- thenAccept: async 실행 결과 값을 받고, 리턴하지 않는 콜백을 실행
- supplyAsync: async 실행 결과 값을 받지 않고, Runnable을 추가로 실행
다수의 태스크를 조합 (thenCompose, thenCombine, allOf, anyOf)
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("꿀똥벌레");
return "꿀똥벌레";
});
future1
.thenCompose(e -> CompletableFuture.supplyAsync(() -> e + " 개발"))
.get()
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "1");
future1
.thenCombine(future2, (str1, str2) -> str1 + str2);
CompletableFuture.allOf(
future1, future2
).thenAccept(e -> {System.out.println("실행 완료");}).get();
CompletableFuture.anyOf(
future1, future2
).thenAccept(e -> {System.out.println("실행 완료");}).get();
- thenCompose: 태스크를 실행하고 그 결과값을 받은 후 다음 태스크를 실행한다.
- 앞선 태스크의 리턴 값이 String이면 thenApply는 string -> string 클로저를 매게변수로 받는다.
- 앞선 태스크의 리턴 값이 String이면 thenCompose는 string -> completionStage<string> 을 받는다.
- thenCombine: 앞선 태스크와 독립적으로 실행하고,(future1, future2 가 독립적으로 실행) 그 결과값 두개를 받은 콜백을 실행한다.
- allOf: 모든 태스크가 실행 완료 되면 thenAccept 콜백이 실행 된다.
- anyOf: 하나의 태스크만 실행 완료 되면 thenAccept 콜백이 실행 된다.
에러 핸들링 (exceptionally, handle, handleAsync)
future1.exceptionally(exception -> {
exception.printStackTrace();
return "에러!";
});
future1.handle((str, exception) -> {
if (exception != null) {
return str;
}
return "에러!";
});
future1.handleAsync((str, exception) -> {
if (exception != null) {
return str;
}
return "에러!";
});
- exceptionally: exception 발생 시에 핸들링 한다.
- handle: 정상 수행, exception 발생 둘다 핸들링 한다.
- handleAsync: handle메소드를 defaultExecutor로 실행한다.
참고
https://mangkyu.tistory.com/263
java doc
'JAVA' 카테고리의 다른 글
JPA @ElementCollection (0) | 2021.05.27 |
---|---|
java annotation (0) | 2021.05.17 |
Jackson 어노테이션 정리 (0) | 2021.04.30 |
JPA 캐시 (0) | 2021.04.28 |
JPA 락 처리 (0) | 2021.04.28 |