30 Kasım 2020 Pazartesi

CompletableFuture.get metodu

Giriş
İmzası şöyle
V get() throws InterruptedException, ExecutionException;
Örnek
Exception'ları fırlattığı için yakalamak gerekir şöyle yaparız.
try {
  CompletableFuture.allOf(fanoutRequestList).get() 
} catch (InterruptedException | ExecutionException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}
Örnek
Tüm işlerin bitmesini beklemek için şöyle yaparız
int TIMEOUT_IN_MILLIS = 100;

@Test
public void allOfOrTimeout() throws InterruptedException, ExecutionException,
TimeoutException
{ getAllOfFuture().get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS); } private CompletableFuture<Void> getAllOfFuture() { return CompletableFuture.allOf( CompletableFuture.runAsync(() -> sleep(1)), CompletableFuture.runAsync(() -> sleep(2)), CompletableFuture.runAsync(() -> sleep(3)), CompletableFuture.runAsync(() -> sleep(4)), CompletableFuture.runAsync(() -> sleep(5)), CompletableFuture.runAsync(() -> sleep(6)), CompletableFuture.runAsync(() -> sleep(7)), CompletableFuture.runAsync(() -> sleep(8)) ); } public static void sleep(int millis) { try { Thread.sleep(millis); System.out.format("Had a nap for %s milliseconds.\r\n", millis); } catch (InterruptedException e) { e.printStackTrace(); } };
Çıktı olarak şunu alırız
Had a nap for 1 milliseconds.
Had a nap for 2 milliseconds.
Had a nap for 3 milliseconds.
Had a nap for 4 milliseconds.
Had a nap for 5 milliseconds.
Had a nap for 6 milliseconds.
Had a nap for 7 milliseconds.
Had a nap for 8 milliseconds.

Hiç yorum yok:

Yorum Gönder