LeoFinance

Asynchrone Programmierung mit Java, allOf und anyOf

4 comments0 reblogs
avatar of @ozelot47
69
ozelot47
@ozelot473 months ago
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 {

    /* in case of multiple futures
     * allOf: Wait until all results from the futures are available
     * anyOf: Wait until one of the results from the futures is available */
    public void listOfCompletableFutures(){
        CompletableFuture<Integer> futureOne = CompletableFuture.supplyAsync(
            () -> {
                return 5;
            }
        );

        CompletableFuture<String> futureTwo = CompletableFuture.supplyAsync(
            () -> {
                return "result";
            }
        );

        CompletableFuture<Integer> futureThree = CompletableFuture.supplyAsync(
            () -> {
                return -61;
            }
        );

        /* Wait for all futures */
        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();

        /* Wait for one of the futures */
        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();
    }
}

Image from thread

4