1 Star 0 Fork 3

artshell/sharecode

forked from dwing/sharecode 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
AsyncFuture.java 2.75 KB
一键复制 编辑 原始数据 按行查看 历史
dwing 提交于 2022-05-15 23:30 +08:00 . test jdk19
package async;
import java.lang.reflect.Field;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import sun.misc.Unsafe;
public class AsyncFuture<T> extends CompletableFuture<T> {
private static final Unsafe unsafe;
private static final long resultOffset;
private Node<T> tail;
private static class Node<T> {
final Function<? super T, ? extends CompletionStage<T>> fn;
Node<T> next;
Node(Function<? super T, ? extends CompletionStage<T>> f) {
fn = f;
}
}
static {
try {
Field theUnsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
theUnsafeField.setAccessible(true);
unsafe = (Unsafe)theUnsafeField.get(null);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
try {
resultOffset = unsafe.objectFieldOffset(CompletableFuture.class.getDeclaredField("result"));
} catch (Exception e) {
throw new Error(e);
}
}
public static <T> AsyncFuture<T> completed(T value) {
AsyncFuture<T> af = new AsyncFuture<>();
af.complete(value);
return af;
}
public AsyncFuture<T> yield() {
unsafe.putObject(this, resultOffset, null);
return this;
}
@SuppressWarnings("unchecked")
@Override
public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) {
Node<T> n = new Node<>((Function<? super T, ? extends CompletionStage<T>>)fn);
Node<T> t = tail;
if (t != null) {
n.next = t.next;
t.next = n;
} else
n.next = n;
tail = n;
return (CompletableFuture<U>)this;
}
@Override
public boolean complete(T value) {
unsafe.putObject(this, resultOffset, value);
Node<T> t = tail;
if (t != null) {
Node<T> n = t.next;
t.next = null;
while (n != null) {
tail = null;
CompletableFuture<T> cf = ((CompletionStage<T>)n.fn.apply(value)).toCompletableFuture();
n = n.next;
unsafe.putObject(this, resultOffset, value = cf.getNow(null));
if (value == null) {
Node<T> tt = tail;
if (tt != null) {
if (n != null) {
Node<T> h = tt.next;
tt.next = n;
t.next = h;
tail = t;
}
break;
}
if (n != null) {
t.next = n;
tail = t;
}
break;
}
}
}
return true;
}
@Override
public boolean isDone() {
return unsafe.getObject(this, resultOffset) != null;
}
@SuppressWarnings("unchecked")
@Override
public T getNow(T valueIfAbsent) {
Object obj = unsafe.getObject(this, resultOffset);
return (obj != null) ? (T)obj : valueIfAbsent;
}
@SuppressWarnings("unchecked")
@Override
public T join() {
return (T)unsafe.getObject(this, resultOffset);
}
@Override
public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn) {
return this;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
其他
1
https://gitee.com/artshell/sharecode.git
git@gitee.com:artshell/sharecode.git
artshell
sharecode
sharecode
main

搜索帮助