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

net.lulihu.promise.Async Maven / Gradle / Ivy

package net.lulihu.promise;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 异步执行工具
 */
public class Async {

    private final static ExecutorService defaultExecutor;

    static {
        int cores = Runtime.getRuntime().availableProcessors();
        defaultExecutor = Executors.newFixedThreadPool(cores);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        defaultExecutor.shutdownNow();
    }

    /**
     * 提交执行
     * 使用默认先线程池
     *
     * @param callable 任务
     * @param       泛型类型
     * @return {@linkplain Promise}
     */
    public static  Promise submit(Callable callable) {
        return submit(callable, defaultExecutor);
    }

    /**
     * 提交执行
     *
     * @param callable        任务
     * @param executorService 任务执行线程池
     * @param              泛型类型
     * @return {@linkplain Promise}
     */
    public static  Promise submit(Callable callable, ExecutorService executorService) {
        final Promise promise = new Promise<>();

        Callable smarterCallable = () -> {
            try {
                V result = callable.call();
                promise.invoke(result);
                return result;
            } catch (Throwable e) {
                promise.invokeWithException(e);
                return null;
            }
        };

        executorService.submit(smarterCallable);
        return promise;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy