본문 바로가기

개발/Java, Spring

비동기처리 - Future의 종류

ListenableFuture

Google이 개발한 guava 오픈소스 라이브러리에 포함되어 있다.

Executor에 task를 제출하고, 돌려 받는 Future 타입의 종류 중 하나이다.

(기존의 Executor 대신 ListeningExecutorService를 사용한다.)

 

Callback method를 생성해서 task가 성공했을 때, 실패했을 때의 작업을 미리 지정해놓을 수 있다.

이렇게 Callback method를 생성하는 것은 Futures를 사용하는 것과 ListenableFuture의 addListener 두 가지가 있다.

 

ListeningExecutor와 task 생성

 

ListeningExecutorService executor =
			MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));

Callable<String> task = new Callable<String>() {
    @Override
    public String call() throws Exception {
    	return "TASK";
    }
};

ListenableFuture<String> listenableFuture = executor.submit(task);

 

Futures를 통한 Callback 등록

 

Futures.addCallback(listenableFuture, new FutureCallback<String>() {
    @Override
    public void onSuccess(String result) {
    	System.out.println("SUCCESS");
    }
    @Override
    public void onFailure(Throwable thrown) {
    	System.out.println("FAILURE : " + thrown.getMessage());
    }    
});

 

ListenableFuture.addListener()

 

listenableFuture.addListener(new Runnable() {
    @Override
    public void run() {
    	try {
        	System.out.println(listenableFuture.get());
        } catch (Exception e) {
        	System.out.prinrln("EXCEPTION : " + e.getMessage());
        }
    }
}, executor);

 

 

참고

api문서

 

ListenableFuture (Guava: Google Core Libraries for Java 21.0 API)

Registers a listener to be run on the given executor. The listener will run when the Future's computation is complete or, if the computation is already complete, immediately. There is no guaranteed ordering of execution of listeners, but any listener added

google.github.io

예제

 

Listen to the Future with Google Guava – Jesper de Jong

Futures are one of the many concepts that are useful for building scalable software. A future is an object that acts as a placeholder for the result of some operation that has yet to be performed. This is useful for asynchronous, non-blocking programming,

www.jesperdj.com

 

 

 

CompletableFuture

비동기 task간의 연결과 그 사이에 발생하는 예외처리 등의 해결을 위해 등장.

 

ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture.runAsync(()->{
    try {
    	Thread.sleep(1000);
    } catch (Exception e) {
    	System.out.println("EXCEPTION");
    }
    
    System.out.println("I'm awake!");
}, executor)
.thenTun(()->System.out.println("Next Job"));

System.out.println("Hello world!");

'개발 > Java, Spring' 카테고리의 다른 글

비동기 처리 - ExecutorService  (0) 2019.03.19