4 Mayıs 2021 Salı

CompletableFuture.whenComplete metodu

Giriş
Açıklaması şöyle
If you need to perform some action, when the previous stage completes normally or exceptionally, you should use the whenComplete method. A BiConsumer argument of the whenComplete method is called when the previous stage completes normally or exceptionally. This method allows reading both the result (or null if none) and the exception (or null if none) but does not allow to change the result.
Açıklaması şöyle.
There are a couple of differences between Task.ContinueWith and CompletableFuture.whenComplete. For one, the function passed into the .Net version takes the Task itself as an argument, requiring an additional step to get its result (or to propagate downstream exceptions if necessary). The function passed into Java version takes the result of the task as an argument.
Eğer CompletableFuture başlamadan veya çalışıyorken whenComplete() metodu eklenirse, whenComplete() ForkJoinPool içinde çalışır.
Eğer CompletableFuture bitmiş iken whenComplete() metodu eklenirse, whenComplete() main thread içinde çalışır.

BiConsumer'a gelen ilk parametre sonuç değeridir. İkinci parametre ise eğer varsa exception nesnesidir.

Eğer CompletableFuture.runAsync() ile başlamışsa BiConsumer'a gelen parametreler null değerine sahiptir.

Örnek
Şöyle yaparız.
CompletableFuture completableFuture = new CompletableFuture();
completableFuture.whenComplete(new BiConsumer() {
  @Override
  public void accept(Object o, Object o2) {
    //handle complete
  }
}); // complete the task
completableFuture.complete(new Object())


Hiç yorum yok:

Yorum Gönder