CompletableFuture

  • 2014년에 발표된 java 8에서 도입
  • 비동기 프로그래밍 지원
  • Lambda, Method reference 등 java 8의 새로운 기능 지원

Method reference

  • ::연산자를 이용하여 함수에 대한 참조를 간결하게 표현
  • method reference
  • static method reference
  • instance method reference
  • constructor method reference
@RequiredArgsConstructor
public static class Person{
    @Getter
    private final String name;

    public Boolean compareTo(Person o){
        return o.name.compareTo(name) > 0;
    }
}

public static void print(String name){
    System.out.println(name);
}

public static void main(String[] args){
    var target = new Person("f");
    Consumer<String> staticPrint = MethodReferenceExample::print;

    Stream.of("a","b","c","d")
            .map(Person::new)// constructor reference
            .filter(target::compareTo)// method reference
            .map(Person::getName)// instance method reference
            .forEach(staticPrint);// static method reference
}

CompletableFuture 클래스

public class CompletableFuture<T> implements
	Future<T>, CompletionStage<T>

Future

  • 비동기적인 작업을 수행
  • 해당 작업이 완료되면 결과를 반환하는 인터페이스

CompletionStage

  • 비동기적인 작업을 수행
  • 해당 작업이 완료되면 결과를 처리하거나 다른 CompletionStage를 연결하는 인터페이스

ExecutorService

  • 쓰레드 풀을 이용하여 비동기적으로 작업을 실행하고 관리
  • 별도의 쓰레드를 생성하고 관리하지 않아도 되므로, 코드를 간결하게 유지 가능
  • 쓰레드 풀을 이용하여 자원을 효율적으로 관리

ExcutorService 메서드

  • execute
    • Runnable 인터페이스를 구현한 작업을 쓰레드 풀에서 비동기적으로 실행
  • submit
    • Callable 인터페이스를 구현한 작업을 쓰레드 풀에서 비동기적으로 실행하고, 해당 작업을 결과를 Future<T> 객체로 반환
  • shutdown
    • ExcutorService를 종료. 더 이상 task를 받지 않는다.

Excutors - ExecutorService 생성

  • newSingleThreadExecutor
    • 단일 쓰레드로 구성된 쓰레드 풀을 생성. 한 번에 하나의 작업만 실행
  • newFixedThreadPool
    • 고정된 크기의 쓰레드 풀을 생성. 크기는 인자로 주어진 n과 동일
  • newCachedThreadPool
    • 사용 가능한 쓰레드가 없다면 새로 생성해서 작업을 처리하고, 있다면 재사용. 스레드가 일정 시간 사용되지 않으면 회수
  • newScheduledThreadPool
    • 스케줄링 기능을 갖춘 고정 크기의 쓰레드 풀을 생성. 주기적이거나 지연이 발생하는 작업을 실행
  • newWorkStealingPool
    • work steal 알고리즘을 사용하는 ForkJoinPool을 생성

Future의 isDone, isCancelled, get, cancel

  • future의 상태를 반환
  • isDone
    • task가 완료되었다면, 원인과 상관없이 true 반환
  • isCancelled
    • task가 명시적으로 취소된 경우, true 반환
  • get
    • 결과를 구할 때까지 thread가 계속 block
    • future에서 무한 루프나 오랜 시간이 걸린다면 thread가 blocking 상태 유지
  • get(long timeout, TimeUnit unit)
    • 결과를 구할 때까지 timeout동안 thread가 block
    • timeout이 넘어가도 응답이 반환되지 않으면 TimeoutException 발생
  • cancel(boolean mayInterruptIfRunnig)
    • future의 작업 실행을 취소
    • 취소할 수 없는 상황이라면 false 반환
    • mayInterruptIfRunning이 false라면 시작하지 않은 작업에 대해서만 취소

Future 인터페이스의 한계

  • cancel을 제외하고 외부에서 future를 컨트롤 할 수 없다.
  • 반환된 결과를 get() 해서 접근하기 때문에 비동기 처리가 어렵다
  • 완료되거나 에러가 발생했는지 구분하기 어렵다

+ Recent posts