mirror of
https://github.com/tommyskeff/futur4j.git
synced 2026-01-18 07:16:45 +00:00
Initial commit
This commit is contained in:
42
futur-api/.gitignore
vendored
Normal file
42
futur-api/.gitignore
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea/modules.xml
|
||||
.idea/jarRepositories.xml
|
||||
.idea/compiler.xml
|
||||
.idea/libraries/
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
34
futur-api/build.gradle.kts
Normal file
34
futur-api/build.gradle.kts
Normal file
@@ -0,0 +1,34 @@
|
||||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("com.github.johnrengelman.shadow") version "7.1.2"
|
||||
}
|
||||
|
||||
group = "dev.tommyjs"
|
||||
version = "1.0.0"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.jetbrains:annotations:24.1.0")
|
||||
implementation("org.slf4j:slf4j-api:2.0.9")
|
||||
testImplementation(platform("org.junit:junit-bom:5.9.1"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||
}
|
||||
|
||||
tasks {
|
||||
build {
|
||||
dependsOn(shadowJar)
|
||||
}
|
||||
|
||||
withType<ShadowJar> {
|
||||
exclude("META-INF/**")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dev.tommyjs.futur.function;
|
||||
|
||||
public interface ExceptionalConsumer<T> {
|
||||
|
||||
void accept(T value) throws Exception;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dev.tommyjs.futur.function;
|
||||
|
||||
public interface ExceptionalFunction<K, V> {
|
||||
|
||||
V apply(K value) throws Exception;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dev.tommyjs.futur.function;
|
||||
|
||||
public interface ExceptionalRunnable {
|
||||
|
||||
void run() throws Exception;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dev.tommyjs.futur.function;
|
||||
|
||||
public interface ExceptionalSupplier<T> {
|
||||
|
||||
T get() throws Exception;
|
||||
|
||||
}
|
||||
404
futur-api/src/main/java/dev/tommyjs/futur/promise/Promise.java
Normal file
404
futur-api/src/main/java/dev/tommyjs/futur/promise/Promise.java
Normal file
@@ -0,0 +1,404 @@
|
||||
package dev.tommyjs.futur.promise;
|
||||
|
||||
import dev.tommyjs.futur.function.ExceptionalConsumer;
|
||||
import dev.tommyjs.futur.function.ExceptionalFunction;
|
||||
import dev.tommyjs.futur.function.ExceptionalRunnable;
|
||||
import dev.tommyjs.futur.function.ExceptionalSupplier;
|
||||
import dev.tommyjs.futur.scheduler.Schedulers;
|
||||
import dev.tommyjs.futur.trace.ExecutorTrace;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Promise<T> {
|
||||
|
||||
private static final String PACKAGE;
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Promise.class);
|
||||
|
||||
static {
|
||||
String[] packageElements = Promise.class.getPackageName().split("\\.");
|
||||
int i = 0;
|
||||
|
||||
StringBuilder packageBuilder = new StringBuilder();
|
||||
while (i < 3) {
|
||||
packageBuilder.append(packageElements[i]);
|
||||
i++;
|
||||
}
|
||||
|
||||
PACKAGE = packageBuilder.toString();
|
||||
}
|
||||
|
||||
private final Collection<PromiseListener<T>> listeners;
|
||||
private final StackTraceElement[] stackTrace;
|
||||
|
||||
private @Nullable PromiseCompletion<T> completion;
|
||||
|
||||
public Promise() {
|
||||
this.listeners = new ConcurrentLinkedQueue<>();
|
||||
this.completion = null;
|
||||
this.stackTrace = Arrays.stream(Thread.currentThread().getStackTrace())
|
||||
.filter(v -> !v.getClassName().startsWith(PACKAGE))
|
||||
.toArray(StackTraceElement[]::new);
|
||||
}
|
||||
|
||||
public T join(long interval, long timeout) throws TimeoutException {
|
||||
long start = System.currentTimeMillis();
|
||||
while (!isCompleted()) {
|
||||
if (System.currentTimeMillis() > start + timeout)
|
||||
throw new TimeoutException("Promise timed out after " + timeout + "ms");
|
||||
|
||||
try {
|
||||
Thread.sleep(interval);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
PromiseCompletion<T> completion = getCompletion();
|
||||
if (completion == null) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
if (completion.isError()) {
|
||||
throw new RuntimeException(completion.getException());
|
||||
}
|
||||
|
||||
return completion.getResult();
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenRunSync(@NotNull ExceptionalRunnable task) {
|
||||
return thenApplySync(result -> {
|
||||
task.run();
|
||||
return null;
|
||||
}, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenRunDelayedSync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedSync(result -> {
|
||||
task.run();
|
||||
return null;
|
||||
}, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenAcceptSync(@NotNull ExceptionalConsumer<T> task) {
|
||||
return thenApplySync(result -> {
|
||||
task.accept(result);
|
||||
return null;
|
||||
}, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenAcceptDelayedSync(@NotNull ExceptionalConsumer<T> task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedSync(result -> {
|
||||
task.accept(result);
|
||||
return null;
|
||||
}, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenSupplySync(@NotNull ExceptionalSupplier<V> task) {
|
||||
return thenApplySync(result -> task.get(), Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenSupplyDelayedSync(@NotNull ExceptionalSupplier<V> task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedSync(result -> task.get(), delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplySync(@NotNull ExceptionalFunction<T, V> task, @NotNull ExecutorTrace trace) {
|
||||
Promise<V> promise = new Promise<>();
|
||||
addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
Runnable runnable = createRunnable(ctx, promise, task);
|
||||
Schedulers.runSync(runnable, trace);
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplySync(@NotNull ExceptionalFunction<T, V> task) {
|
||||
return thenApplySync(task, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplyDelayedSync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
Promise<V> promise = new Promise<>();
|
||||
addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
Runnable runnable = createRunnable(ctx, promise, task);
|
||||
Schedulers.runDelayedSync(runnable, delay, unit, trace);
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplyDelayedSync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedSync(task, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenComposeSync(@NotNull ExceptionalFunction<T, @NotNull Promise<V>> task) {
|
||||
Promise<V> promise = new Promise<>();
|
||||
thenApplySync(task, Schedulers.getTrace(task)).thenAcceptAsync(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());
|
||||
}
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenRunAsync(@NotNull ExceptionalRunnable task) {
|
||||
return thenApplyAsync(result -> {
|
||||
task.run();
|
||||
return null;
|
||||
}, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenRunDelayedAsync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedAsync(result -> {
|
||||
task.run();
|
||||
return null;
|
||||
}, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenAcceptAsync(@NotNull ExceptionalConsumer<T> task) {
|
||||
return thenApplyAsync(result -> {
|
||||
task.accept(result);
|
||||
return null;
|
||||
}, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public @NotNull Promise<Void> thenAcceptDelayedAsync(@NotNull ExceptionalConsumer<T> task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedAsync(result -> {
|
||||
task.accept(result);
|
||||
return null;
|
||||
}, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenSupplyAsync(@NotNull ExceptionalSupplier<V> task) {
|
||||
return thenApplyAsync(result -> task.get(), Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenSupplyDelayedAsync(@NotNull ExceptionalSupplier<V> task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedAsync(result -> task.get(), delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public @NotNull Promise<T> thenPopulateReference(@NotNull AtomicReference<T> reference) {
|
||||
return thenApplyAsync((result) -> {
|
||||
reference.set(result);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplyAsync(@NotNull ExceptionalFunction<T, V> task, @NotNull ExecutorTrace trace) {
|
||||
Promise<V> promise = new Promise<>();
|
||||
addListener(ctx -> {
|
||||
createRunnable(ctx, promise, task).run();
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplyAsync(@NotNull ExceptionalFunction<T, V> task) {
|
||||
return thenApplyAsync(task, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplyDelayedAsync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
Promise<V> promise = new Promise<>();
|
||||
addListener(ctx -> {
|
||||
Runnable runnable = createRunnable(ctx, promise, task);
|
||||
Schedulers.runDelayedAsync(runnable, delay, unit, trace);
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenApplyDelayedAsync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit) {
|
||||
return thenApplyDelayedAsync(task, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenCompose(@NotNull ExceptionalFunction<T, Promise<V>> task) {
|
||||
return this.thenComposeAsync(task);
|
||||
}
|
||||
|
||||
public <V> @NotNull Promise<V> thenComposeAsync(@NotNull ExceptionalFunction<T, Promise<V>> task) {
|
||||
Promise<V> promise = new Promise<>();
|
||||
thenApplyAsync(task, Schedulers.getTrace(task)).thenAcceptAsync(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());
|
||||
}
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
private <V> @NotNull Runnable createRunnable(@NotNull PromiseCompletion<T> ctx, @NotNull Promise<V> promise, @NotNull ExceptionalFunction<T, V> task) {
|
||||
return () -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
V result = task.apply(ctx.getResult());
|
||||
promise.complete(result);
|
||||
} catch (Exception e) {
|
||||
promise.completeExceptionally(e, true);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public @NotNull Promise<T> logExceptions() {
|
||||
return addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
LOGGER.error("Exception caught in promise pipeline", ctx.getException());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public @NotNull Promise<T> addListener(@NotNull PromiseListener<T> listener) {
|
||||
if (isCompleted()) {
|
||||
Schedulers.runAsync(() -> {
|
||||
try {
|
||||
listener.handle(getCompletion());
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Exception caught in promise listener", e);
|
||||
}
|
||||
}, Schedulers.getTrace(listener));
|
||||
} else {
|
||||
getListeners().add(listener);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public @NotNull Promise<T> timeout(long time, @NotNull TimeUnit unit) {
|
||||
Schedulers.runDelayedAsync(() -> {
|
||||
if (!isCompleted()) {
|
||||
completeExceptionally(new TimeoutException("Promise timed out after " + time + " " + unit), true);
|
||||
}
|
||||
}, time, unit);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public @NotNull Promise<T> timeout(long ms) {
|
||||
return timeout(ms, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
protected void handleCompletion(@NotNull PromiseCompletion<T> ctx) {
|
||||
if (this.isCompleted()) return;
|
||||
setCompletion(ctx);
|
||||
|
||||
Schedulers.runAsync(() -> {
|
||||
for (PromiseListener<T> listener : getListeners()) {
|
||||
if (!ctx.isActive()) return;
|
||||
|
||||
try {
|
||||
listener.handle(ctx);
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Exception caught in promise listener", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void complete(@Nullable T result) {
|
||||
handleCompletion(new PromiseCompletion<>(result));
|
||||
}
|
||||
|
||||
public void completeExceptionally(@NotNull Throwable result, boolean appendStacktrace) {
|
||||
if (appendStacktrace && this.stackTrace != null) {
|
||||
result.setStackTrace(Stream.of(result.getStackTrace(), this.stackTrace)
|
||||
.flatMap(Stream::of)
|
||||
.filter(v -> !v.getClassName().startsWith(PACKAGE))
|
||||
.filter(v -> !v.getClassName().startsWith("java.lang.Thread"))
|
||||
.filter(v -> !v.getClassName().startsWith("java.util.concurrent"))
|
||||
.toArray(StackTraceElement[]::new));
|
||||
}
|
||||
|
||||
handleCompletion(new PromiseCompletion<>(result));
|
||||
}
|
||||
|
||||
public void completeExceptionally(@NotNull Throwable result) {
|
||||
completeExceptionally(result, false);
|
||||
}
|
||||
|
||||
public boolean isCompleted() {
|
||||
return getCompletion() != null;
|
||||
}
|
||||
|
||||
protected Collection<PromiseListener<T>> getListeners() {
|
||||
return listeners;
|
||||
}
|
||||
|
||||
public @Nullable PromiseCompletion<T> getCompletion() {
|
||||
return completion;
|
||||
}
|
||||
|
||||
protected void setCompletion(@NotNull PromiseCompletion<T> completion) {
|
||||
this.completion = completion;
|
||||
}
|
||||
|
||||
public static <T> @NotNull Promise<T> resolve(T value) {
|
||||
Promise<T> promise = new Promise<>();
|
||||
promise.setCompletion(new PromiseCompletion<>(value));
|
||||
return promise;
|
||||
}
|
||||
|
||||
public static <T> @NotNull Promise<T> error(Throwable error) {
|
||||
Promise<T> promise = new Promise<>();
|
||||
promise.completeExceptionally(error);
|
||||
return promise;
|
||||
}
|
||||
|
||||
public static @NotNull Promise<Void> start() {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
@Deprecated // use resolve()
|
||||
public static <T> @NotNull Promise<T> start(T start) {
|
||||
Promise<T> promise = new Promise<>();
|
||||
promise.complete(start);
|
||||
return promise;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package dev.tommyjs.futur.promise;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PromiseCompletion<T> {
|
||||
|
||||
private @Nullable T result;
|
||||
private @Nullable Throwable exception;
|
||||
private boolean active;
|
||||
|
||||
public PromiseCompletion(@Nullable T result) {
|
||||
this.result = result;
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public PromiseCompletion(@NotNull Throwable exception) {
|
||||
this.exception = exception;
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public PromiseCompletion() {
|
||||
this.result = null;
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public void markHandled() {
|
||||
this.active = false;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public boolean isError() {
|
||||
return getException() != null;
|
||||
}
|
||||
|
||||
public @Nullable T getResult() {
|
||||
return result;
|
||||
}
|
||||
|
||||
public @Nullable Throwable getException() {
|
||||
return exception;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dev.tommyjs.futur.promise;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface PromiseListener<T> {
|
||||
|
||||
void handle(@NotNull PromiseCompletion<T> ctx);
|
||||
|
||||
}
|
||||
173
futur-api/src/main/java/dev/tommyjs/futur/promise/Promises.java
Normal file
173
futur-api/src/main/java/dev/tommyjs/futur/promise/Promises.java
Normal file
@@ -0,0 +1,173 @@
|
||||
package dev.tommyjs.futur.promise;
|
||||
|
||||
import dev.tommyjs.futur.function.ExceptionalFunction;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.*;
|
||||
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;
|
||||
|
||||
public class Promises {
|
||||
|
||||
public static <K, V> @NotNull Promise<Map.Entry<K, V>> combine(@NotNull Promise<K> p1, @NotNull Promise<V> p2) {
|
||||
Promise<Map.Entry<K, V>> promise = new Promise<>();
|
||||
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;
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises, long timeout, @Nullable BiConsumer<K, Throwable> exceptionHandler) {
|
||||
Map<K, V> map = new HashMap<>();
|
||||
if (promises.isEmpty()) return Promise.resolve(map);
|
||||
|
||||
ReentrantLock lock = new ReentrantLock();
|
||||
|
||||
Promise<Map<K, V>> promise = new Promise<>();
|
||||
for (Map.Entry<K, Promise<V>> entry : promises.entrySet()) {
|
||||
entry.getValue().addListener((ctx) -> {
|
||||
lock.lock();
|
||||
|
||||
try {
|
||||
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);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
});
|
||||
}
|
||||
return promise.timeout(timeout);
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises, long timeout, boolean strict) {
|
||||
return combine(promises, timeout, strict ? null : (_k, _v) -> {});
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises, long timeout) {
|
||||
return combine(promises, timeout, true);
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Map<K, Promise<V>> promises) {
|
||||
return combine(promises, 1500L, true);
|
||||
}
|
||||
|
||||
public static <V> @NotNull Promise<List<V>> combine(@NotNull List<Promise<V>> promises, long timeout, boolean strict) {
|
||||
AtomicInteger index = new AtomicInteger();
|
||||
return combine(
|
||||
promises.stream()
|
||||
.collect(Collectors.toMap(s -> index.getAndIncrement(), v -> v)),
|
||||
timeout,
|
||||
strict
|
||||
).thenApplySync(v ->
|
||||
v.entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
}
|
||||
|
||||
public static <V> @NotNull Promise<List<V>> combine(@NotNull List<Promise<V>> promises, long timeout) {
|
||||
return combine(promises, timeout, true);
|
||||
}
|
||||
|
||||
public static <V> @NotNull Promise<List<V>> combine(@NotNull List<Promise<V>> promises) {
|
||||
return combine(promises, 1500L, true);
|
||||
}
|
||||
|
||||
public static @NotNull Promise<Void> all(@NotNull List<Promise<?>> promises) {
|
||||
if (promises.isEmpty()) return Promise.start();
|
||||
|
||||
Promise<Void> promise = new Promise<>();
|
||||
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;
|
||||
}
|
||||
|
||||
public static @NotNull Promise<Void> all(@NotNull Promise<?>... promises) {
|
||||
return all(Arrays.asList(promises));
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Collection<K> keys, @NotNull ExceptionalFunction<K, V> mapper, long timeout, boolean strict) {
|
||||
Map<K, Promise<V>> promises = new HashMap<>();
|
||||
for (K key : keys) {
|
||||
Promise<V> promise = Promise.resolve(key).thenApplyAsync(mapper);
|
||||
promises.put(key, promise);
|
||||
}
|
||||
|
||||
return combine(promises, timeout, strict);
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Collection<K> keys, @NotNull ExceptionalFunction<K, V> mapper, long timeout) {
|
||||
return combine(keys, mapper, timeout, true);
|
||||
}
|
||||
|
||||
public static <K, V> @NotNull Promise<Map<K, V>> combine(@NotNull Collection<K> keys, @NotNull ExceptionalFunction<K, V> mapper) {
|
||||
return combine(keys, mapper, 1500L, true);
|
||||
}
|
||||
|
||||
public static @NotNull Promise<Void> erase(@NotNull Promise<?> p) {
|
||||
Promise<Void> promise = new Promise<>();
|
||||
p.addListener(ctx -> {
|
||||
if (ctx.isError()) {
|
||||
//noinspection ConstantConditions
|
||||
promise.completeExceptionally(ctx.getException());
|
||||
} else {
|
||||
promise.complete(null);
|
||||
}
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
public static <T> @NotNull Promise<T> wrap(@NotNull CompletableFuture<T> future) {
|
||||
Promise<T> promise = new Promise<>();
|
||||
future.whenComplete((result, e) -> {
|
||||
if (e != null) {
|
||||
promise.completeExceptionally(e);
|
||||
} else {
|
||||
promise.complete(result);
|
||||
}
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dev.tommyjs.futur.scheduler;
|
||||
|
||||
import dev.tommyjs.futur.trace.ExecutorTrace;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public interface Scheduler {
|
||||
|
||||
Logger LOGGER = LoggerFactory.getLogger(Scheduler.class);
|
||||
|
||||
void runSync(@NotNull Runnable task, @NotNull ExecutorTrace trace);
|
||||
|
||||
void runDelayedSync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace);
|
||||
|
||||
void runRepeatingSync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace);
|
||||
|
||||
void runAsync(@NotNull Runnable task, @NotNull ExecutorTrace trace);
|
||||
|
||||
void runDelayedAsync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace);
|
||||
|
||||
void runRepeatingAsync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace);
|
||||
|
||||
default @NotNull Runnable wrapExceptions(@NotNull Runnable task, @NotNull ExecutorTrace trace) {
|
||||
return () -> {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Exception in scheduled task: {}", e.getClass().getName());
|
||||
LOGGER.error(trace.toString());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package dev.tommyjs.futur.scheduler;
|
||||
|
||||
import dev.tommyjs.futur.trace.ExecutorTrace;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
public class Schedulers {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Schedulers.class);
|
||||
|
||||
private static @Nullable Scheduler scheduler;
|
||||
|
||||
public static void runSync(@NotNull Runnable task, @NotNull ExecutorTrace trace) {
|
||||
ensureLoaded();
|
||||
getScheduler().runSync(task, trace);
|
||||
}
|
||||
|
||||
public static void runSync(@NotNull Runnable task) {
|
||||
ensureLoaded();
|
||||
getScheduler().runSync(task, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public static void runDelayedSync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
ensureLoaded();
|
||||
getScheduler().runDelayedSync(task, delay, unit, trace);
|
||||
}
|
||||
|
||||
public static void runDelayedSync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit) {
|
||||
ensureLoaded();
|
||||
getScheduler().runDelayedSync(task, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public static void runRepeatingSync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
ensureLoaded();
|
||||
getScheduler().runRepeatingSync(task, interval, unit, trace);
|
||||
}
|
||||
|
||||
public static void runRepeatingSync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit) {
|
||||
ensureLoaded();
|
||||
getScheduler().runRepeatingSync(task, interval, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public static void runAsync(@NotNull Runnable task, @NotNull ExecutorTrace trace) {
|
||||
ensureLoaded();
|
||||
getScheduler().runAsync(task, trace);
|
||||
}
|
||||
|
||||
public static void runAsync(@NotNull Runnable task) {
|
||||
ensureLoaded();
|
||||
getScheduler().runAsync(task, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public static void runDelayedAsync(@NotNull Runnable task, long delay, TimeUnit unit, ExecutorTrace trace) {
|
||||
ensureLoaded();
|
||||
getScheduler().runDelayedAsync(task, delay, unit, trace);
|
||||
}
|
||||
|
||||
public static void runDelayedAsync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit) {
|
||||
ensureLoaded();
|
||||
getScheduler().runDelayedAsync(task, delay, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public static void runRepeatingAsync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
ensureLoaded();
|
||||
getScheduler().runRepeatingAsync(task, interval, unit, trace);
|
||||
}
|
||||
|
||||
public static void runRepeatingAsync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit) {
|
||||
ensureLoaded();
|
||||
getScheduler().runRepeatingAsync(task, interval, unit, Schedulers.getTrace(task));
|
||||
}
|
||||
|
||||
public static ExecutorTrace getTrace(@NotNull Object function) {
|
||||
return new ExecutorTrace(function.getClass(), Thread.currentThread().getStackTrace());
|
||||
}
|
||||
|
||||
public static void ensureLoaded() {
|
||||
if (getScheduler() == null) {
|
||||
LOGGER.warn("No scheduler loaded, falling back to default single threaded scheduler");
|
||||
setScheduler(SingleExecutorScheduler.create());
|
||||
}
|
||||
}
|
||||
|
||||
public static void loadDefaultScheduler() {
|
||||
|
||||
}
|
||||
|
||||
public static boolean isLoaded() {
|
||||
return getScheduler() != null;
|
||||
}
|
||||
|
||||
public static @Nullable Scheduler getScheduler() {
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
public static void setScheduler(@NotNull Scheduler scheduler) {
|
||||
Schedulers.scheduler = scheduler;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package dev.tommyjs.futur.scheduler;
|
||||
|
||||
import dev.tommyjs.futur.trace.ExecutorTrace;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class SingleExecutorScheduler implements Scheduler {
|
||||
|
||||
private final ScheduledExecutorService service;
|
||||
|
||||
protected SingleExecutorScheduler(ScheduledExecutorService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runSync(@NotNull Runnable task, @NotNull ExecutorTrace trace) {
|
||||
service.submit(wrapExceptions(task, trace));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runDelayedSync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
service.schedule(wrapExceptions(task, trace), delay, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runRepeatingSync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
service.scheduleAtFixedRate(wrapExceptions(task, trace), 0L, interval, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runAsync(@NotNull Runnable task, @NotNull ExecutorTrace trace) {
|
||||
runSync(task, trace);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runDelayedAsync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
runDelayedSync(task, delay, unit, trace);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runRepeatingAsync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) {
|
||||
runRepeatingSync(task, interval, unit, trace);
|
||||
}
|
||||
|
||||
public static SingleExecutorScheduler create() {
|
||||
return new SingleExecutorScheduler(Executors.newSingleThreadScheduledExecutor());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package dev.tommyjs.futur.trace;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ExecutorTrace {
|
||||
|
||||
private final @NotNull Class<?> clazz;
|
||||
private final @NotNull StackTraceElement[] trace;
|
||||
|
||||
public ExecutorTrace(@NotNull Class<?> clazz, @NotNull StackTraceElement[] trace) {
|
||||
this.clazz = clazz;
|
||||
this.trace = trace;
|
||||
}
|
||||
|
||||
public @NotNull Class<?> getClazz() {
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public @NotNull StackTraceElement[] getTrace() {
|
||||
return trace;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return Arrays.stream(trace).map(StackTraceElement::toString).collect(Collectors.joining("\n"));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user