Programing/Java

CompletableFuture

BUST 2018. 9. 15. 20:18

CompletableFuture 



Example

supplyAsync 메서드를 이용한 방식

CompletableFuture<String> future
  = CompletableFuture.supplyAsync(() -> "Hello");
 
// ...
 
assertEquals("Hello", future.get());


thenApply 메서드를 이용한 결과값 처리

CompletableFuture<String> completableFuture
  = CompletableFuture.supplyAsync(() -> "Hello");
 
CompletableFuture<String> future = completableFuture
  .thenApply(s -> s + " World");
 
assertEquals("Hello World", future.get());


thenCompose를 이용하여 Future을 이용하여 처리하기

CompletableFuture<String> completableFuture 
  = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
 
assertEquals("Hello World", completableFuture.get());


multiple futures

CompletableFuture<String> future1  
  = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2  
  = CompletableFuture.supplyAsync(() -> "Beautiful");
CompletableFuture<String> future3  
  = CompletableFuture.supplyAsync(() -> "World");
 
CompletableFuture<Void> combinedFuture 
  = CompletableFuture.allOf(future1, future2, future3);
 
// ...
 
combinedFuture.get();
 
assertTrue(future1.isDone());
assertTrue(future2.isDone());
assertTrue(future3.isDone());


stream을 이용하여 결과값 합치기

String combined = Stream.of(future1, future2, future3)
  .map(CompletableFuture::join)
  .collect(Collectors.joining(" "));
 
assertEquals("Hello Beautiful World", combined);


에러 핸들링

String name = null;
 
// ...
 
CompletableFuture<String> completableFuture  
  =  CompletableFuture.supplyAsync(() -> {
      if (name == null) {
          throw new RuntimeException("Computation error!");
      }
      return "Hello, " + name;
  })}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
 
assertEquals("Hello, Stranger!", completableFuture.get());


Async Method

CompletableFuture<String> completableFuture  
  = CompletableFuture.supplyAsync(() -> "Hello");
 
CompletableFuture<String> future = completableFuture
  .thenApplyAsync(s -> s + " World");
 
assertEquals("Hello World", future.get());



Custom ExecutorService

private static ExecutorService service = Executors.newCachedThreadPool();

CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> System.out.println("running async task"), service);
  • 기본적으로 PorkJoinPool.commonPool()를 사용하기 때문에 Executor Service를 활용해서 성능을 상승 시킬수가 있다.


'Programing > Java' 카테고리의 다른 글

Java Jdbc를 이용한 데이터베이스 접근하기  (0) 2018.10.23
Guava Eventbus @AllowConcurrentEvents  (0) 2018.10.10
Guava Cache  (0) 2018.09.12
Singleton Pattern  (0) 2018.09.06
SLF4J(Simple Logging Facade for Java)  (0) 2018.09.01