其他分享
首页 > 其他分享> > ActiveJ框架学习——Async I/O之promise

ActiveJ框架学习——Async I/O之promise

作者:互联网

2021SC@SDUSC

概述

我们先来看一下官网对promise的介绍:

    Promises are primary building blocks in the ActiveJ async programming model which can be compared to Java Futures. promise represents the result of an operation that hasn't been completed yet.

        promise是ActiveJ异步编程模型的主要构件,可以与Java Futures相比较。promise代表一个尚未完成的操作的结果。

        那么,什么是Futures?Future是在JDK5中新加入的用来获取异步执行结果。从功能上来讲,Future表示一个可能还没有完成的异步任务的结果,针对这个结果可以添加Callback以便在任务执行成功或失败后作出相应的操作。后因其局限,在JDK8中补充了它的新特性CompletableFuture与CompletionStage。

特点

  • 与Java Futures不同, Promises ,被设计为在一个单一的事件循环线程中工作。
  • Promises 是非常轻量级的
  • 没有多线程的开销
  • 每秒可处理数百万次呼叫
  • 用于组合多个promise的强大的API

 源码目录结构

分析

        用以下方法可以创造一个promise。

Promise<Integer> firstNumber = Promise.of(10);
Promise.of("Hello World");
Promise.ofException(new Exception("Something went wrong") );

 其中:

    static <T> @NotNull Promise<T> of(@Nullable T value) {
        return value != null ? new CompleteResultPromise<>(value) : CompleteNullPromise.instance();
    }

 

    static <T> @NotNull Promise<T> ofException(@NotNull Exception e) {
		return new CompleteExceptionallyPromise<>(e);
	}

此外,我们还有一种快捷创建 Promise.of(null) 的方式。

	static @NotNull Promise<Void> complete() {
		return (Promise<Void>) CompleteNullPromise.INSTANCE;
	}

标签:Futures,ofException,value,ActiveJ,promise,Promise,NotNull,Async
来源: https://blog.csdn.net/m0_46761289/article/details/120813743