Posts

Asynchrone Programmierung mit Java, allOf und anyOf

avatar of @ozelot47
25
@ozelot47
·
0 views
·
1 min read

Mit der Funktion allOf wird solange auf die Ergebnisse aller Futures gewartet bevor der Code weiterläuft. Mit anyOf hingegen wird nur auf das schnellste Ergebnis gewartet.

import java.util.concurrent.CompletableFuture; 
 
public class Asynchron { 
 
    /<em> in case of multiple futures 
     </em> allOf: Wait until all results from the futures are available 
     <em> anyOf: Wait until one of the results from the futures is available </em>/ 
    public void listOfCompletableFutures(){ 
        CompletableFuture<Integer> futureOne = CompletableFuture.supplyAsync( 
            () -> { 
                return 5; 
            } 
        ); 
 
        CompletableFuture<String> futureTwo = CompletableFuture.supplyAsync( 
            () -> { 
                return "result"; 
            } 
        ); 
 
        CompletableFuture<Integer> futureThree = CompletableFuture.supplyAsync( 
            () -> { 
                return -61; 
            } 
        ); 
 
        /<em> Wait for all futures </em>/ 
        CompletableFuture<Void> futurelist = CompletableFuture.allOf(futureOne, futureTwo, futureThree) 
        .thenAccept( 
            (result) -> { 
                System.out.println(futureOne.join()); 
                System.out.println(futureTwo.join()); 
                System.out.println(futureThree.join()); 
            } 
        ); 
        futurelist.join(); 
 
        /<em> Wait for one of the futures </em>/ 
        CompletableFuture<Object> any = CompletableFuture.anyOf(futureOne, futureTwo, futureThree); 
        Object fastesResult = any.join(); 
        System.out.println(fastesResult); 
 
    } 
     
    public static void main(String[] args){ 
        Asynchron async = new Asynchron(); 
        async.listOfCompletableFutures(); 
    } 
}