All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.iohao.game.common.kit.CompletableFutureKit Maven / Gradle / Ivy

/*
 * ioGame
 * Copyright (C) 2021 - present  渔民小镇 ([email protected][email protected]) . All Rights Reserved.
 * # iohao.com . 渔民小镇
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see .
 */
package com.iohao.game.common.kit;

import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * CompletableFuture Kit
 *
 * @author 渔民小镇
 * @date 2022-07-27
 */
@UtilityClass
public class CompletableFutureKit {
    static final CompletableFuture[] EMPTY_ARRAY = new CompletableFuture[0];

    /**
     * 并行调用多个 CompletableFuture 结果
     *
     * @param futures futures
     * @param      t
     * @return 结果集
     */
    public  List sequence(List> futures) {
        // 组合处理 allOf
        CompletableFuture allDoneFuture = CompletableFuture.allOf(futures.toArray(EMPTY_ARRAY));

        return allDoneFuture.thenApply(v ->
                futures.stream()
                        .map(CompletableFuture::join)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList())
        ).join();

        // see https://nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html
    }

    public  CompletableFuture> sequenceAsync(List> futures) {
        // see https://nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html

        return CompletableFuture.allOf(futures.toArray(EMPTY_ARRAY)).thenApply(v -> {
            // join all
            return futures.stream()
                    .map(CompletableFuture::join)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        });
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy