4 Mayıs 2021 Salı

CompletableFuture.handle metodu - State Normal veya Hatalı Bitse de Çağrılır

Giriş
Açıklaması şöyle
If you need to recover from an exception (to replace the exception with some default value), you should use the handle and exceptionally methods. A BiFunction argument of the handle method is called when the previous stage completes normally or exceptionally. A Function argument of the exceptionally method is called when the previous stage completes exceptionally. In both cases, an exception is not propagated to the next stage.
Açıklaması şöyle
returns a new CompletionStage that upon normal or exceptional completion transforms the result or exception of this stage and returns the new result
Açıklaması şöyle
This method takes a BiFunction as an argument:
- Result and Exception are parameters ( one is null )
- This method will always be executed regardless of whether an exception occurs or not allowing you to recover or throw an exception downstream
Bir önceki CompletionStage bitince çağrılır. Eğer exception olursa birinci parametre null, ikinci parametre exception'dır. 
Örnek
Şöyle yaparız.
public static F.Promise<Void> performAllItemsBackup(Stream<Item> stream) {
  return F.Promise.pure(stream).flatMap(items -> {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    try {
      return CompletableFuture.allOf(
        items.map(CompletableFuture::completedFuture)
             .map(f -> f.thenAcceptAsync(performSingleItemBackup, pool))
             .toArray(CompletableFuture<?>[]::new))
             .handle((v, e) -> e!=null? F.Promise.<Void>throwing(e): F.Promise.pure(v))
             .join();
    } finally {
      pool.shutdown();
    }
  });
}

Hiç yorum yok:

Yorum Gönder