mirror of
https://github.com/tommyskeff/futur4j.git
synced 2026-01-18 07:16:45 +00:00
add cancellation and refractor PromiseFactory
This commit is contained in:
@@ -10,12 +10,14 @@ import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class AbstractPromise<T> implements Promise<T> {
|
||||
public abstract class AbstractPromise<T, F> implements Promise<T> {
|
||||
|
||||
private final Collection<PromiseListener<T>> listeners;
|
||||
private final AtomicReference<PromiseCompletion<T>> completion;
|
||||
@@ -25,14 +27,14 @@ public abstract class AbstractPromise<T> implements Promise<T> {
|
||||
this.completion = new AtomicReference<>();
|
||||
}
|
||||
|
||||
protected abstract PromiseExecutor getExecutor();
|
||||
public abstract @NotNull AbstractPromiseFactory<F> getFactory();
|
||||
|
||||
protected abstract Logger getLogger();
|
||||
protected @NotNull PromiseExecutor<F> getExecutor() {
|
||||
return getFactory().getExecutor();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public T join(long interval, long timeoutMillis) throws TimeoutException {
|
||||
return join(timeoutMillis);
|
||||
protected @NotNull Logger getLogger() {
|
||||
return getFactory().getLogger();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -56,7 +58,7 @@ public abstract class AbstractPromise<T> implements Promise<T> {
|
||||
}
|
||||
|
||||
if (completion == null)
|
||||
throw new TimeoutException("Promise timed out after " + timeoutMillis + "ms");
|
||||
throw new TimeoutException("Promise stopped waiting after " + timeoutMillis + "ms");
|
||||
|
||||
return joinCompletion(completion);
|
||||
}
|
||||
@@ -113,57 +115,47 @@ public abstract class AbstractPromise<T> implements Promise<T> {
|
||||
@Override
|
||||
public <V> @NotNull Promise<V> thenApplySync(@NotNull ExceptionalFunction<T, V> task) {
|
||||
Promise<V> promise = getFactory().unresolved();
|
||||
addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
Runnable runnable = createRunnable(ctx, promise, task);
|
||||
getExecutor().runSync(runnable, 0L, TimeUnit.MILLISECONDS);
|
||||
});
|
||||
addListener(
|
||||
res -> {
|
||||
Runnable runnable = createRunnable(res, promise, task);
|
||||
F future = getExecutor().runSync(runnable);
|
||||
promise.onCancel((e) -> getExecutor().cancel(future));
|
||||
},
|
||||
promise::completeExceptionally
|
||||
);
|
||||
|
||||
addChild(promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> @NotNull Promise<V> thenApplyDelayedSync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit) {
|
||||
Promise<V> promise = getFactory().unresolved();
|
||||
addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
Runnable runnable = createRunnable(ctx, promise, task);
|
||||
getExecutor().runSync(runnable, delay, unit);
|
||||
});
|
||||
addListener(
|
||||
res -> {
|
||||
Runnable runnable = createRunnable(res, promise, task);
|
||||
F future = getExecutor().runSync(runnable, delay, unit);
|
||||
promise.onCancel((e) -> getExecutor().cancel(future));
|
||||
},
|
||||
promise::completeExceptionally
|
||||
);
|
||||
|
||||
addChild(promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> @NotNull Promise<V> thenComposeSync(@NotNull ExceptionalFunction<T, @NotNull Promise<V>> task) {
|
||||
Promise<V> promise = getFactory().unresolved();
|
||||
thenApplySync(task).thenConsumeAsync(nestedPromise -> {
|
||||
nestedPromise.addListener(ctx1 -> {
|
||||
if (ctx1.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx1.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
promise.complete(ctx1.getResult());
|
||||
});
|
||||
}).addListener(ctx2 -> {
|
||||
if (ctx2.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx2.getException());
|
||||
}
|
||||
});
|
||||
thenApplySync(task).addListener(
|
||||
nestedPromise -> {
|
||||
nestedPromise.propagateResult(promise);
|
||||
nestedPromise.addChild(promise);
|
||||
},
|
||||
promise::completeExceptionally
|
||||
);
|
||||
|
||||
addChild(promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@@ -220,83 +212,66 @@ public abstract class AbstractPromise<T> implements Promise<T> {
|
||||
@Override
|
||||
public <V> @NotNull Promise<V> thenApplyAsync(@NotNull ExceptionalFunction<T, V> task) {
|
||||
Promise<V> promise = getFactory().unresolved();
|
||||
addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
Runnable runnable = createRunnable(ctx, promise, task);
|
||||
getExecutor().runAsync(runnable, 0L, TimeUnit.MILLISECONDS);
|
||||
});
|
||||
addListener(
|
||||
(res) -> {
|
||||
Runnable runnable = createRunnable(res, promise, task);
|
||||
F future = getExecutor().runAsync(runnable);
|
||||
promise.onCancel((e) -> getExecutor().cancel(future));
|
||||
},
|
||||
promise::completeExceptionally
|
||||
);
|
||||
|
||||
addChild(promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> @NotNull Promise<V> thenApplyDelayedAsync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit) {
|
||||
Promise<V> promise = getFactory().unresolved();
|
||||
addListener(ctx -> {
|
||||
Runnable runnable = createRunnable(ctx, promise, task);
|
||||
getExecutor().runAsync(runnable, delay, unit);
|
||||
});
|
||||
addListener(
|
||||
res -> {
|
||||
Runnable runnable = createRunnable(res, promise, task);
|
||||
F future = getExecutor().runAsync(runnable, delay, unit);
|
||||
promise.onCancel((e) -> getExecutor().cancel(future));
|
||||
},
|
||||
promise::completeExceptionally
|
||||
);
|
||||
|
||||
addChild(promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> @NotNull Promise<V> thenComposeAsync(@NotNull ExceptionalFunction<T, Promise<V>> task) {
|
||||
Promise<V> promise = getFactory().unresolved();
|
||||
thenApplyAsync(task).thenConsumeAsync(nestedPromise -> {
|
||||
nestedPromise.addListener(ctx1 -> {
|
||||
if (ctx1.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx1.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
promise.complete(ctx1.getResult());
|
||||
});
|
||||
}).addListener(ctx2 -> {
|
||||
if (ctx2.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx2.getException());
|
||||
}
|
||||
});
|
||||
thenApplyAsync(task).addListener(
|
||||
nestedPromise -> {
|
||||
nestedPromise.propagateResult(promise);
|
||||
nestedPromise.addChild(promise);
|
||||
},
|
||||
promise::completeExceptionally
|
||||
);
|
||||
|
||||
addChild(promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
private <V> @NotNull Runnable createRunnable(@NotNull PromiseCompletion<T> ctx, @NotNull Promise<V> promise, @NotNull ExceptionalFunction<T, V> task) {
|
||||
private <V> @NotNull Runnable createRunnable(T result, @NotNull Promise<V> promise, @NotNull ExceptionalFunction<T, V> task) {
|
||||
return () -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
if (promise.isCompleted()) return;
|
||||
|
||||
try {
|
||||
V result = task.apply(ctx.getResult());
|
||||
promise.complete(result);
|
||||
V nextResult = task.apply(result);
|
||||
promise.complete(nextResult);
|
||||
} catch (Throwable e) {
|
||||
promise.completeExceptionally(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<T> logExceptions() {
|
||||
return logExceptions("Exception caught in promise chain");
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<T> logExceptions(@NotNull String message) {
|
||||
return addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
getLogger().error(message, ctx.getException());
|
||||
}
|
||||
});
|
||||
return onError(e -> getLogger().error(message, e));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -320,19 +295,51 @@ public abstract class AbstractPromise<T> implements Promise<T> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<T> timeout(long time, @NotNull TimeUnit unit) {
|
||||
getExecutor().runAsync(() -> {
|
||||
if (!isCompleted()) {
|
||||
completeExceptionally(new TimeoutException("Promise timed out after " + time + " " + unit));
|
||||
public @NotNull Promise<T> addListener(@Nullable Consumer<T> successListener, @Nullable Consumer<Throwable> errorListener) {
|
||||
return addListener((res) -> {
|
||||
if (res.isError()) {
|
||||
if (errorListener != null) errorListener.accept(res.getException());
|
||||
} else {
|
||||
if (successListener != null) successListener.accept(res.getResult());
|
||||
}
|
||||
}, time, unit);
|
||||
|
||||
return this;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<T> timeout(long ms) {
|
||||
return timeout(ms, TimeUnit.MILLISECONDS);
|
||||
public @NotNull Promise<T> onSuccess(@NotNull Consumer<T> listener) {
|
||||
return addListener(listener, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<T> onError(@NotNull Consumer<Throwable> listener) {
|
||||
return addListener(null, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends Throwable> @NotNull Promise<T> onError(@NotNull Class<E> clazz, @NotNull Consumer<E> listener) {
|
||||
return onError((e) -> {
|
||||
if (clazz.isAssignableFrom(e.getClass())) {
|
||||
//noinspection unchecked
|
||||
listener.accept((E) e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<T> onCancel(@NotNull Consumer<CancellationException> listener) {
|
||||
return onError(CancellationException.class, listener);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public @NotNull Promise<T> timeout(long time, @NotNull TimeUnit unit) {
|
||||
return maxWaitTime(time, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<T> maxWaitTime(long time, @NotNull TimeUnit unit) {
|
||||
F future = getExecutor().runAsync(() -> completeExceptionally(new TimeoutException("Promise stopped waiting after " + time + " " + unit)), time, unit);
|
||||
return onError(e -> getExecutor().cancel(future));
|
||||
}
|
||||
|
||||
private void handleCompletion(@NotNull PromiseCompletion<T> ctx) {
|
||||
@@ -358,6 +365,26 @@ public abstract class AbstractPromise<T> implements Promise<T> {
|
||||
return this.completion.compareAndSet(null, completion);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addChild(@NotNull Promise<?> child) {
|
||||
child.onCancel((e) -> this.cancel(e.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void propagateResult(@NotNull Promise<T> target) {
|
||||
addListener(target::complete, target::completeExceptionally);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
completeExceptionally(new CancellationException());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel(@NotNull String message) {
|
||||
completeExceptionally(new CancellationException(message));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void complete(@Nullable T result) {
|
||||
handleCompletion(new PromiseCompletion<>(result));
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package dev.tommyjs.futur.promise;
|
||||
|
||||
import dev.tommyjs.futur.executor.PromiseExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
public abstract class AbstractPromiseFactory<F> implements PromiseFactory {
|
||||
|
||||
public abstract @NotNull PromiseExecutor<F> getExecutor();
|
||||
|
||||
@Override
|
||||
public <K, V> @NotNull Promise<Map.Entry<K, V>> combine(@NotNull Promise<K> p1, @NotNull Promise<V> p2) {
|
||||
List<Promise<?>> promises = List.of(p1, p2);
|
||||
return all(promises)
|
||||
.thenApplyAsync((res) -> new AbstractMap.SimpleImmutableEntry<>(
|
||||
Objects.requireNonNull(p1.getCompletion()).getResult(),
|
||||
Objects.requireNonNull(p2.getCompletion()).getResult()
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises, @Nullable BiConsumer<K, Throwable> exceptionHandler) {
|
||||
if (promises.isEmpty()) return resolve(Collections.emptyMap());
|
||||
|
||||
Map<K, V> map = new HashMap<>();
|
||||
Promise<Map<K, V>> promise = unresolved();
|
||||
for (Map.Entry<K, Promise<V>> entry : promises.entrySet()) {
|
||||
entry.getValue().addListener((ctx) -> {
|
||||
synchronized (map) {
|
||||
if (ctx.getException() != null) {
|
||||
if (exceptionHandler == null) {
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
} else {
|
||||
exceptionHandler.accept(entry.getKey(), ctx.getException());
|
||||
map.put(entry.getKey(), null);
|
||||
}
|
||||
} else {
|
||||
map.put(entry.getKey(), ctx.getResult());
|
||||
}
|
||||
|
||||
if (map.size() == promises.size()) {
|
||||
promise.complete(map);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> @NotNull Promise<List<V>> combine(@NotNull Iterable<Promise<V>> promises, @Nullable Consumer<Throwable> exceptionHandler) {
|
||||
AtomicInteger index = new AtomicInteger();
|
||||
return this.combine(
|
||||
StreamSupport.stream(promises.spliterator(), false)
|
||||
.collect(Collectors.toMap(k -> index.getAndIncrement(), v -> v)),
|
||||
exceptionHandler != null ? (i, e) -> exceptionHandler.accept(e) : null
|
||||
).thenApplyAsync(v ->
|
||||
v.entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> @NotNull Promise<List<V>> combine(@NotNull Iterable<Promise<V>> promises) {
|
||||
return combine(promises, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<List<PromiseCompletion<?>>> allSettled(@NotNull Iterable<Promise<?>> promiseIterable) {
|
||||
List<Promise<?>> promises = new ArrayList<>();
|
||||
promiseIterable.iterator().forEachRemaining(promises::add);
|
||||
|
||||
if (promises.isEmpty()) return resolve(Collections.emptyList());
|
||||
PromiseCompletion<?>[] results = new PromiseCompletion<?>[promises.size()];
|
||||
|
||||
Promise<List<PromiseCompletion<?>>> promise = unresolved();
|
||||
var iter = promises.listIterator();
|
||||
|
||||
while (iter.hasNext()) {
|
||||
int index = iter.nextIndex();
|
||||
iter.next().addListener((res) -> {
|
||||
synchronized (results) {
|
||||
results[index] = res;
|
||||
if (Arrays.stream(results).allMatch(Objects::nonNull))
|
||||
promise.complete(Arrays.asList(results));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<Void> all(@NotNull Iterable<Promise<?>> promiseIterable) {
|
||||
List<Promise<?>> promises = new ArrayList<>();
|
||||
promiseIterable.iterator().forEachRemaining(promises::add);
|
||||
|
||||
if (promises.isEmpty()) return resolve(null);
|
||||
AtomicInteger completed = new AtomicInteger();
|
||||
Promise<Void> promise = unresolved();
|
||||
|
||||
for (Promise<?> p : promises) {
|
||||
p.addListener((res) -> {
|
||||
if (res.getException() != null) {
|
||||
promise.completeExceptionally(res.getException());
|
||||
}
|
||||
|
||||
if (completed.incrementAndGet() == promises.size()) {
|
||||
promise.complete(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @NotNull Promise<T> wrap(@NotNull CompletableFuture<T> future) {
|
||||
Promise<T> promise = unresolved();
|
||||
|
||||
future.whenComplete((v, e) -> {
|
||||
if (e != null) {
|
||||
promise.completeExceptionally(e);
|
||||
} else {
|
||||
promise.complete(v);
|
||||
}
|
||||
});
|
||||
|
||||
promise.onCancel((e) -> future.cancel(true));
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @NotNull Promise<T> wrap(@NotNull Mono<T> mono) {
|
||||
Promise<T> promise = this.unresolved();
|
||||
Disposable disposable = mono.subscribe(promise::complete, promise::completeExceptionally);
|
||||
promise.onCancel((e) -> disposable.dispose());
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @NotNull Promise<T> resolve(T value) {
|
||||
Promise<T> promise = unresolved();
|
||||
promise.complete(value);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @NotNull Promise<T> error(@NotNull Throwable error) {
|
||||
Promise<T> promise = unresolved();
|
||||
promise.completeExceptionally(error);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Promise<Void> erase(@NotNull Promise<?> p) {
|
||||
Promise<Void> promise = unresolved();
|
||||
p.addListener(ctx -> {
|
||||
if (ctx.getException() != null) {
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
} else {
|
||||
promise.complete(null);
|
||||
}
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,35 +7,16 @@ import dev.tommyjs.futur.function.ExceptionalSupplier;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface Promise<T> {
|
||||
|
||||
static <T> @NotNull Promise<T> resolve(T value, PromiseFactory factory) {
|
||||
return factory.resolve(value);
|
||||
}
|
||||
|
||||
static <T> @NotNull Promise<T> error(Throwable error, PromiseFactory factory) {
|
||||
return factory.error(error);
|
||||
}
|
||||
|
||||
static <T> @NotNull Promise<T> unresolved(PromiseFactory factory) {
|
||||
return factory.unresolved();
|
||||
}
|
||||
|
||||
static @NotNull Promise<Void> start(PromiseFactory factory) {
|
||||
return factory.resolve(null);
|
||||
}
|
||||
|
||||
PromiseFactory getFactory();
|
||||
|
||||
@Deprecated
|
||||
T join(long interval, long timeout) throws TimeoutException;
|
||||
|
||||
T join(long timeout) throws TimeoutException;
|
||||
|
||||
@NotNull Promise<Void> thenRunSync(@NotNull ExceptionalRunnable task);
|
||||
|
||||
@NotNull Promise<Void> thenRunDelayedSync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit);
|
||||
@@ -74,22 +55,56 @@ public interface Promise<T> {
|
||||
|
||||
<V> @NotNull Promise<V> thenComposeAsync(@NotNull ExceptionalFunction<T, Promise<V>> task);
|
||||
|
||||
@NotNull Promise<T> logExceptions();
|
||||
|
||||
@NotNull Promise<T> logExceptions(@NotNull String message);
|
||||
|
||||
default @NotNull Promise<T> logExceptions() {
|
||||
return logExceptions("Exception caught in promise chain");
|
||||
}
|
||||
|
||||
@NotNull Promise<T> addListener(@NotNull PromiseListener<T> listener);
|
||||
|
||||
@NotNull Promise<T> addListener(@Nullable Consumer<T> successHandler, @Nullable Consumer<Throwable> errorHandler);
|
||||
|
||||
@NotNull Promise<T> onSuccess(@NotNull Consumer<T> listener);
|
||||
|
||||
@NotNull Promise<T> onError(@NotNull Consumer<Throwable> listener);
|
||||
|
||||
<E extends Throwable> @NotNull Promise<T> onError(@NotNull Class<E> clazz, @NotNull Consumer<E> listener);
|
||||
|
||||
@NotNull Promise<T> onCancel(@NotNull Consumer<CancellationException> listener);
|
||||
|
||||
@Deprecated
|
||||
@NotNull Promise<T> timeout(long time, @NotNull TimeUnit unit);
|
||||
|
||||
@NotNull Promise<T> timeout(long ms);
|
||||
@Deprecated
|
||||
default @NotNull Promise<T> timeout(long ms) {
|
||||
return timeout(ms, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
@NotNull Promise<T> maxWaitTime(long time, @NotNull TimeUnit unit);
|
||||
|
||||
default @NotNull Promise<T> maxWaitTime(long ms) {
|
||||
return maxWaitTime(ms, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
void addChild(@NotNull Promise<?> child);
|
||||
|
||||
void propagateResult(@NotNull Promise<T> target);
|
||||
|
||||
void cancel(@Nullable String reason);
|
||||
|
||||
default void cancel() {
|
||||
cancel(null);
|
||||
}
|
||||
|
||||
void complete(@Nullable T result);
|
||||
|
||||
void completeExceptionally(@NotNull Throwable result);
|
||||
|
||||
boolean isCompleted();
|
||||
T join(long timeout) throws TimeoutException;
|
||||
|
||||
@Nullable PromiseCompletion<T> getCompletion();
|
||||
|
||||
boolean isCompleted();
|
||||
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package dev.tommyjs.futur.promise;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.concurrent.CancellationException;
|
||||
|
||||
public class PromiseCompletion<T> {
|
||||
|
||||
private @Nullable T result;
|
||||
@@ -36,6 +38,10 @@ public class PromiseCompletion<T> {
|
||||
return getException() != null;
|
||||
}
|
||||
|
||||
public boolean wasCanceled() {
|
||||
return getException() instanceof CancellationException;
|
||||
}
|
||||
|
||||
public @Nullable T getResult() {
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1,36 +1,61 @@
|
||||
package dev.tommyjs.futur.promise;
|
||||
|
||||
import dev.tommyjs.futur.executor.PromiseExecutor;
|
||||
import dev.tommyjs.futur.executor.SinglePoolExecutor;
|
||||
import dev.tommyjs.futur.impl.SimplePromiseFactory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface PromiseFactory {
|
||||
|
||||
<T> @NotNull Promise<T> resolve(T value);
|
||||
@NotNull Logger getLogger();
|
||||
|
||||
<T> @NotNull Promise<T> unresolved();
|
||||
|
||||
<T> @NotNull Promise<T> error(Throwable error);
|
||||
<K, V> @NotNull Promise<Map.Entry<K, V>> combine(@NotNull Promise<K> p1, @NotNull Promise<V> p2);
|
||||
|
||||
static PromiseFactory create(PromiseExecutor executor, Logger logger) {
|
||||
return new SimplePromiseFactory(executor, logger);
|
||||
<K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises, @Nullable BiConsumer<K, Throwable> exceptionHandler);
|
||||
|
||||
default <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises) {
|
||||
return combine(promises, null);
|
||||
}
|
||||
|
||||
static PromiseFactory create(PromiseExecutor executor) {
|
||||
return create(executor, LoggerFactory.getLogger(SimplePromiseFactory.class));
|
||||
<V> @NotNull Promise<List<V>> combine(@NotNull Iterable<Promise<V>> promises, @Nullable Consumer<Throwable> exceptionHandler);
|
||||
|
||||
default <V> @NotNull Promise<List<V>> combine(@NotNull Iterable<Promise<V>> promises) {
|
||||
return combine(promises, null);
|
||||
}
|
||||
|
||||
static PromiseFactory create(int threadPoolSize) {
|
||||
return create(SinglePoolExecutor.create(threadPoolSize));
|
||||
@NotNull Promise<List<PromiseCompletion<?>>> allSettled(@NotNull Iterable<Promise<?>> promiseIterable);
|
||||
|
||||
default @NotNull Promise<List<PromiseCompletion<?>>> allSettled(@NotNull Promise<?>... promiseArray) {
|
||||
return allSettled(Arrays.asList(promiseArray));
|
||||
}
|
||||
|
||||
static PromiseFactory create() {
|
||||
return create(Runtime.getRuntime().availableProcessors());
|
||||
@NotNull Promise<Void> all(@NotNull Iterable<Promise<?>> promiseIterable);
|
||||
|
||||
default @NotNull Promise<Void> all(@NotNull Promise<?>... promiseArray) {
|
||||
return all(Arrays.asList(promiseArray));
|
||||
}
|
||||
|
||||
<T> @NotNull Promise<T> wrap(@NotNull CompletableFuture<T> future);
|
||||
|
||||
<T> @NotNull Promise<T> wrap(@NotNull Mono<T> mono);
|
||||
|
||||
<T> @NotNull Promise<T> resolve(T value);
|
||||
|
||||
default @NotNull Promise<Void> start() {
|
||||
return resolve(null);
|
||||
}
|
||||
|
||||
<T> @NotNull Promise<T> error(@NotNull Throwable error);
|
||||
|
||||
@NotNull Promise<Void> erase(@NotNull Promise<?> p);
|
||||
|
||||
}
|
||||
|
||||
@@ -4,37 +4,21 @@ import dev.tommyjs.futur.function.ExceptionalFunction;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @deprecated Use PromiseFactory instance methods instead.
|
||||
*/
|
||||
@Deprecated
|
||||
public class Promises {
|
||||
|
||||
public static <K, V> @NotNull Promise<Map.Entry<K, V>> combine(@NotNull Promise<K> p1, @NotNull Promise<V> p2, PromiseFactory factory) {
|
||||
Promise<Map.Entry<K, V>> promise = factory.unresolved();
|
||||
p1.addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
p2.addListener(ctx1 -> {
|
||||
if (ctx1.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx1.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
Map.Entry<K, V> result = new AbstractMap.SimpleEntry<>(ctx.getResult(), ctx1.getResult());
|
||||
promise.complete(result);
|
||||
});
|
||||
});
|
||||
|
||||
return promise;
|
||||
return factory.combine(p1, p2);
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map.Entry<K, V>> combine(@NotNull Promise<K> p1, @NotNull Promise<V> p2) {
|
||||
@@ -42,29 +26,7 @@ public class Promises {
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises, long timeout, @Nullable BiConsumer<K, Throwable> exceptionHandler, PromiseFactory factory) {
|
||||
if (promises.isEmpty()) return factory.resolve(Collections.emptyMap());
|
||||
|
||||
Map<K, V> map = new HashMap<>();
|
||||
Promise<Map<K, V>> promise = factory.unresolved();
|
||||
for (Map.Entry<K, Promise<V>> entry : promises.entrySet()) {
|
||||
entry.getValue().addListener((ctx) -> {
|
||||
synchronized (map) {
|
||||
if (ctx.isError()) {
|
||||
if (exceptionHandler == null) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
} else {
|
||||
exceptionHandler.accept(entry.getKey(), ctx.getException());
|
||||
map.put(entry.getKey(), null);
|
||||
}
|
||||
} else {
|
||||
map.put(entry.getKey(), ctx.getResult());
|
||||
}
|
||||
if (map.size() == promises.size()) promise.complete(map);
|
||||
}
|
||||
});
|
||||
}
|
||||
return promise.timeout(timeout);
|
||||
return factory.combine(promises, exceptionHandler).timeout(timeout);
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises, long timeout, boolean strict, PromiseFactory factory) {
|
||||
@@ -80,16 +42,7 @@ public class Promises {
|
||||
}
|
||||
|
||||
public static <V> @NotNull Promise<List<V>> combine(@NotNull List<Promise<V>> promises, long timeout, boolean strict, PromiseFactory factory) {
|
||||
AtomicInteger index = new AtomicInteger();
|
||||
return combine(
|
||||
promises.stream().collect(Collectors.toMap(s -> index.getAndIncrement(), v -> v)),
|
||||
timeout, strict, factory
|
||||
).thenApplySync(v ->
|
||||
v.entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
return factory.combine(promises, strict ? null : (_v) -> {}).timeout(timeout);
|
||||
}
|
||||
|
||||
public static <V> @NotNull Promise<List<V>> combine(@NotNull List<Promise<V>> promises, long timeout, PromiseFactory factory) {
|
||||
@@ -101,20 +54,7 @@ public class Promises {
|
||||
}
|
||||
|
||||
public static @NotNull Promise<Void> all(@NotNull List<Promise<?>> promises, PromiseFactory factory) {
|
||||
if (promises.isEmpty()) return factory.resolve(null);
|
||||
|
||||
Promise<Void> promise = factory.unresolved();
|
||||
for (Promise<?> p : promises) {
|
||||
p.addListener((ctx) -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
} else if (promises.stream().allMatch(Promise::isCompleted)) {
|
||||
promise.complete(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
return promise;
|
||||
return factory.all(promises);
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Collection<K> keys, @NotNull ExceptionalFunction<K, V> mapper, long timeout, boolean strict, PromiseFactory factory) {
|
||||
@@ -136,17 +76,7 @@ public class Promises {
|
||||
}
|
||||
|
||||
public static @NotNull Promise<Void> erase(@NotNull Promise<?> p, PromiseFactory factory) {
|
||||
Promise<Void> promise = factory.unresolved();
|
||||
p.addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
} else {
|
||||
promise.complete(null);
|
||||
}
|
||||
});
|
||||
|
||||
return promise;
|
||||
return factory.erase(p);
|
||||
}
|
||||
|
||||
public static @NotNull Promise<Void> erase(@NotNull Promise<?> p) {
|
||||
@@ -154,16 +84,7 @@ public class Promises {
|
||||
}
|
||||
|
||||
public static <T> @NotNull Promise<T> wrap(@NotNull CompletableFuture<T> future, PromiseFactory factory) {
|
||||
Promise<T> promise = factory.unresolved();
|
||||
future.whenComplete((result, e) -> {
|
||||
if (e != null) {
|
||||
promise.completeExceptionally(e);
|
||||
} else {
|
||||
promise.complete(result);
|
||||
}
|
||||
});
|
||||
|
||||
return promise;
|
||||
return factory.wrap(future);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user