완료 가능향후 개선 예정
CompletableFuture
- get() 메서드는 Future 계산이 완료될 때까지 차단 상태로 유지되므로 비동기 프로그래밍의 설계 철학에 위배되는 방식으로 차단됩니다.
- isDene() 메서드는 CPU 리소스를 소모하는 경향이 있습니다.
- 진정한 비동기 처리를 위해서는 Future가 끝날 때 자동으로 호출되는 콜백 함수를 전달하여 결과를 기다릴 필요가 없도록 하는 것이 좋습니다.
완료 가능 미래 및 완료 단계 소개
클래스 아키텍처 설명:
인터페이스 완료 단계
한 단계가 완료되면 다른 단계가 트리거될 수 있는 비동기 계산 프로세스의 단계를 나타냅니다. 한 단계의 실행은 단일 단계의 완료에 의해 트리거되거나 여러 단계가 함께 트리거될 수 있습니다.
CompletableFuture 클래스
비동기 프로그래밍의 복잡성을 단순화하는 데 도움이 되는 Future에 대한 매우 강력한 확장을 제공하며 함수형 프로그래밍이 콜백을 통해 계산 결과를 처리하는 기능과 CompletableFuture를 변환 및 결합하는 메서드를 제공합니다. 명확하게 완료된 Future를 나타내거나 완료 단계를 나타낼 수 있으며, 다음과 같은 기능을 지원할 수 있습니다. 명확하게 완료된 Future 또는 계산이 완료된 후 일부 함수를 트리거하거나 일부 작업을 수행하는 기능을 지원하는 완료 단계를 나타낼 수 있습니다.
비동기 작업을 생성하는 코어의 네 가지 정적 메서드
네 가지 정적 생성자
위의 Executor 매개변수 설명: 지정하지 않으면 기본 ForkJoinPool commonPool()이 비동기 코드를 실행하는 스레드 풀로 사용되고, 스레드 풀이 지정되면 사용자 정의 또는 특별히 지정된 스레드 풀이 비동기 코드를 실행하는 데 사용됩니다.
package com.kwfruit.thread.step01;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Slf4j
public class CompletableFutureBuildDemo {
@SneakyThrows
public static void main(String[] args) {
/**
* 반환값 없음
*/
ExecutorService executorService = Executors.newFixedThreadPool(3);
CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(()->{
log.debug(Thread.currentThread().getName());
try {TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName());
},executorService);
System.out.println(completableFuture1.get());
/**
* 반환 값
*/
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(()->{
log.debug(Thread.currentThread().getName());
try {TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName());
return "hello supplyAsync";
});
System.out.println(completableFuture.get());
}
}





