代码拉取完成,页面将自动刷新
同步操作将从 dwing/sharecode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。