JAVA/JAVA8 관련
CompletableFuture1
JUMP개발자
2022. 5. 31. 14:55
CompletableFuture :
- 자바에서 비동기 프로그래밍을 지원하는 인터페이스임.
- Future에서 하기 어려웠던 작업들을 수월하게 할 수 있음.
Future에서 하기 어려웠던 작업들
1) Future를 외부에서 완료시킬 수 없다.
취소하거나 get()에 타임아웃을 설정할 수 없다.
2) 블로킹 코드(get())를 사용하지 않고서는 작업이 끝났을 때 콜백을 실행할 수 없음.
-> Future를 통해 결과값을 만들고 무언가를 하는 작업은 get() 이후에 와야한다.
3) 여러 Future를 조합할 수 없다. 예) 이벤트 정보를 가져온 다음에 이벤트에 참여한 회원 목록 가져오기
4) 예외처리용 API를 제공하지 않는다.
비동기로 작업 실행하기
- 리턴값이 없는 작업 : runAsync() 사용
- 리턴값이 있는 작업 : supplyAsync() 사용
콜백 제공하는 방식
- thenApply(Function) : 리턴값을 받아서 다른 값으로 바꾸는 콜백
- thenAccept(Consumer) : 리턴값을 Callback에서 받아서, 작업을 처리하는 방식(리턴 없이)
- thenRun(Runnable) : 리턴값을 받지 않고 다른 작업을 처리하는 콜백
public class CompletableFutureP {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 리턴타입이 없는경우
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("1. No ReturnType :: " + Thread.currentThread().getName());
});
future.get();
System.out.println("=====================================");
// 리턴타입이 있는경우
CompletableFuture<String> returnFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("2. Yes ReturnType :: " + Thread.currentThread().getName());
return "Hi returnCheck";
});
System.out.println(returnFuture.get());
System.out.println("=====================================");
// 리턴타입이 있는경우(thenApply 사용)
CompletableFuture<String> futureThenApply = CompletableFuture.supplyAsync(() -> {
System.out.println("3. Return thenApply :: " + Thread.currentThread().getName());
return "Hi ThenApply ";
}).thenApply((s) -> {
System.out.println(Thread.currentThread().getName());
return s.toUpperCase();
});
System.out.println(futureThenApply.get());
System.out.println("=====================================");
// 리턴값을 받아서 다른 값으로 바꾸는 콜백(thenAccept 사용)
CompletableFuture<Void> futureThenAccept = CompletableFuture.supplyAsync(() -> {
System.out.println("4. Return thenAccept :: " + Thread.currentThread().getName());
return "Hi ThenAccept";
}).thenAccept((s) -> {
System.out.println(Thread.currentThread().getName());
System.out.println(s.toUpperCase());
});
System.out.println("=====================================");
// 리턴타입이 있는경우(thenRun 사용)
CompletableFuture<Void> futureThenRun = CompletableFuture.supplyAsync(() -> {
System.out.println("5. Return thenRun :: " + Thread.currentThread().getName());
return "Hi ThenRun";
}).thenRun(() -> {
System.out.println(Thread.currentThread().getName());
});
System.out.println("=====================================");
}
}