commit 08e97d81a420a1b4cc6c3b91a89e624b5cf00d8d Author: tommyskeff Date: Sun Nov 19 20:55:02 2023 +0000 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/.gitignore @@ -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 \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f898628 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 tommyskeff + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fd41dea --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# Futur4J + +Futur4J is a powerful and intuitive open-source Java library that simplifies asynchronous task scheduling, inspired by the concept of JavaScript promises. + +## Getting Started +Coming Soon + +## Documentation +Coming Soon + diff --git a/futur-api/.gitignore b/futur-api/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/futur-api/.gitignore @@ -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 \ No newline at end of file diff --git a/futur-api/build.gradle.kts b/futur-api/build.gradle.kts new file mode 100644 index 0000000..cc370ea --- /dev/null +++ b/futur-api/build.gradle.kts @@ -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 { + exclude("META-INF/**") + } +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalConsumer.java b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalConsumer.java new file mode 100644 index 0000000..a5f57c3 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalConsumer.java @@ -0,0 +1,7 @@ +package dev.tommyjs.futur.function; + +public interface ExceptionalConsumer { + + void accept(T value) throws Exception; + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalFunction.java b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalFunction.java new file mode 100644 index 0000000..4a7d575 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalFunction.java @@ -0,0 +1,7 @@ +package dev.tommyjs.futur.function; + +public interface ExceptionalFunction { + + V apply(K value) throws Exception; + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalRunnable.java b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalRunnable.java new file mode 100644 index 0000000..6c11ba5 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalRunnable.java @@ -0,0 +1,7 @@ +package dev.tommyjs.futur.function; + +public interface ExceptionalRunnable { + + void run() throws Exception; + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalSupplier.java b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalSupplier.java new file mode 100644 index 0000000..f82800c --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/function/ExceptionalSupplier.java @@ -0,0 +1,7 @@ +package dev.tommyjs.futur.function; + +public interface ExceptionalSupplier { + + T get() throws Exception; + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/promise/Promise.java b/futur-api/src/main/java/dev/tommyjs/futur/promise/Promise.java new file mode 100644 index 0000000..c8fb4b3 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/promise/Promise.java @@ -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 { + + 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> listeners; + private final StackTraceElement[] stackTrace; + + private @Nullable PromiseCompletion 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 completion = getCompletion(); + if (completion == null) { + throw new IllegalStateException(); + } + + if (completion.isError()) { + throw new RuntimeException(completion.getException()); + } + + return completion.getResult(); + } + + public @NotNull Promise thenRunSync(@NotNull ExceptionalRunnable task) { + return thenApplySync(result -> { + task.run(); + return null; + }, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenRunDelayedSync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedSync(result -> { + task.run(); + return null; + }, delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenAcceptSync(@NotNull ExceptionalConsumer task) { + return thenApplySync(result -> { + task.accept(result); + return null; + }, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenAcceptDelayedSync(@NotNull ExceptionalConsumer task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedSync(result -> { + task.accept(result); + return null; + }, delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenSupplySync(@NotNull ExceptionalSupplier task) { + return thenApplySync(result -> task.get(), Schedulers.getTrace(task)); + } + + public @NotNull Promise thenSupplyDelayedSync(@NotNull ExceptionalSupplier task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedSync(result -> task.get(), delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenApplySync(@NotNull ExceptionalFunction task, @NotNull ExecutorTrace trace) { + Promise 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 @NotNull Promise thenApplySync(@NotNull ExceptionalFunction task) { + return thenApplySync(task, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenApplyDelayedSync(@NotNull ExceptionalFunction task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + Promise 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 @NotNull Promise thenApplyDelayedSync(@NotNull ExceptionalFunction task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedSync(task, delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenComposeSync(@NotNull ExceptionalFunction> task) { + Promise 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 thenRunAsync(@NotNull ExceptionalRunnable task) { + return thenApplyAsync(result -> { + task.run(); + return null; + }, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenRunDelayedAsync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedAsync(result -> { + task.run(); + return null; + }, delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenAcceptAsync(@NotNull ExceptionalConsumer task) { + return thenApplyAsync(result -> { + task.accept(result); + return null; + }, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenAcceptDelayedAsync(@NotNull ExceptionalConsumer task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedAsync(result -> { + task.accept(result); + return null; + }, delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenSupplyAsync(@NotNull ExceptionalSupplier task) { + return thenApplyAsync(result -> task.get(), Schedulers.getTrace(task)); + } + + public @NotNull Promise thenSupplyDelayedAsync(@NotNull ExceptionalSupplier task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedAsync(result -> task.get(), delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenPopulateReference(@NotNull AtomicReference reference) { + return thenApplyAsync((result) -> { + reference.set(result); + return result; + }); + } + + public @NotNull Promise thenApplyAsync(@NotNull ExceptionalFunction task, @NotNull ExecutorTrace trace) { + Promise promise = new Promise<>(); + addListener(ctx -> { + createRunnable(ctx, promise, task).run(); + }); + + return promise; + } + + public @NotNull Promise thenApplyAsync(@NotNull ExceptionalFunction task) { + return thenApplyAsync(task, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenApplyDelayedAsync(@NotNull ExceptionalFunction task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + Promise promise = new Promise<>(); + addListener(ctx -> { + Runnable runnable = createRunnable(ctx, promise, task); + Schedulers.runDelayedAsync(runnable, delay, unit, trace); + }); + + return promise; + } + + public @NotNull Promise thenApplyDelayedAsync(@NotNull ExceptionalFunction task, long delay, @NotNull TimeUnit unit) { + return thenApplyDelayedAsync(task, delay, unit, Schedulers.getTrace(task)); + } + + public @NotNull Promise thenCompose(@NotNull ExceptionalFunction> task) { + return this.thenComposeAsync(task); + } + + public @NotNull Promise thenComposeAsync(@NotNull ExceptionalFunction> task) { + Promise 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 @NotNull Runnable createRunnable(@NotNull PromiseCompletion ctx, @NotNull Promise promise, @NotNull ExceptionalFunction 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 logExceptions() { + return addListener(ctx -> { + if (ctx.isError()) { + LOGGER.error("Exception caught in promise pipeline", ctx.getException()); + } + }); + } + + public @NotNull Promise addListener(@NotNull PromiseListener 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 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 timeout(long ms) { + return timeout(ms, TimeUnit.MILLISECONDS); + } + + protected void handleCompletion(@NotNull PromiseCompletion ctx) { + if (this.isCompleted()) return; + setCompletion(ctx); + + Schedulers.runAsync(() -> { + for (PromiseListener 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> getListeners() { + return listeners; + } + + public @Nullable PromiseCompletion getCompletion() { + return completion; + } + + protected void setCompletion(@NotNull PromiseCompletion completion) { + this.completion = completion; + } + + public static @NotNull Promise resolve(T value) { + Promise promise = new Promise<>(); + promise.setCompletion(new PromiseCompletion<>(value)); + return promise; + } + + public static @NotNull Promise error(Throwable error) { + Promise promise = new Promise<>(); + promise.completeExceptionally(error); + return promise; + } + + public static @NotNull Promise start() { + return Promise.resolve(null); + } + + @Deprecated // use resolve() + public static @NotNull Promise start(T start) { + Promise promise = new Promise<>(); + promise.complete(start); + return promise; + } + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/promise/PromiseCompletion.java b/futur-api/src/main/java/dev/tommyjs/futur/promise/PromiseCompletion.java new file mode 100644 index 0000000..c98411a --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/promise/PromiseCompletion.java @@ -0,0 +1,47 @@ +package dev.tommyjs.futur.promise; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class PromiseCompletion { + + 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; + } + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/promise/PromiseListener.java b/futur-api/src/main/java/dev/tommyjs/futur/promise/PromiseListener.java new file mode 100644 index 0000000..7ec1a26 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/promise/PromiseListener.java @@ -0,0 +1,9 @@ +package dev.tommyjs.futur.promise; + +import org.jetbrains.annotations.NotNull; + +public interface PromiseListener { + + void handle(@NotNull PromiseCompletion ctx); + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/promise/Promises.java b/futur-api/src/main/java/dev/tommyjs/futur/promise/Promises.java new file mode 100644 index 0000000..7ecf0c4 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/promise/Promises.java @@ -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 @NotNull Promise> combine(@NotNull Promise p1, @NotNull Promise p2) { + Promise> 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 result = new AbstractMap.SimpleEntry<>(ctx.getResult(), ctx1.getResult()); + promise.complete(result); + }); + }); + + return promise; + } + + public static @NotNull Promise> combine(@NotNull Map> promises, long timeout, @Nullable BiConsumer exceptionHandler) { + Map map = new HashMap<>(); + if (promises.isEmpty()) return Promise.resolve(map); + + ReentrantLock lock = new ReentrantLock(); + + Promise> promise = new Promise<>(); + for (Map.Entry> 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 @NotNull Promise> combine(@NotNull Map> promises, long timeout, boolean strict) { + return combine(promises, timeout, strict ? null : (_k, _v) -> {}); + } + + public static @NotNull Promise> combine(@NotNull Map> promises, long timeout) { + return combine(promises, timeout, true); + } + + public static @NotNull Promise> combine(@NotNull Map> promises) { + return combine(promises, 1500L, true); + } + + public static @NotNull Promise> combine(@NotNull List> 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 @NotNull Promise> combine(@NotNull List> promises, long timeout) { + return combine(promises, timeout, true); + } + + public static @NotNull Promise> combine(@NotNull List> promises) { + return combine(promises, 1500L, true); + } + + public static @NotNull Promise all(@NotNull List> promises) { + if (promises.isEmpty()) return Promise.start(); + + Promise 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 all(@NotNull Promise... promises) { + return all(Arrays.asList(promises)); + } + + public static @NotNull Promise> combine(@NotNull Collection keys, @NotNull ExceptionalFunction mapper, long timeout, boolean strict) { + Map> promises = new HashMap<>(); + for (K key : keys) { + Promise promise = Promise.resolve(key).thenApplyAsync(mapper); + promises.put(key, promise); + } + + return combine(promises, timeout, strict); + } + + public static @NotNull Promise> combine(@NotNull Collection keys, @NotNull ExceptionalFunction mapper, long timeout) { + return combine(keys, mapper, timeout, true); + } + + public static @NotNull Promise> combine(@NotNull Collection keys, @NotNull ExceptionalFunction mapper) { + return combine(keys, mapper, 1500L, true); + } + + public static @NotNull Promise erase(@NotNull Promise p) { + Promise promise = new Promise<>(); + p.addListener(ctx -> { + if (ctx.isError()) { + //noinspection ConstantConditions + promise.completeExceptionally(ctx.getException()); + } else { + promise.complete(null); + } + }); + + return promise; + } + + public static @NotNull Promise wrap(@NotNull CompletableFuture future) { + Promise promise = new Promise<>(); + future.whenComplete((result, e) -> { + if (e != null) { + promise.completeExceptionally(e); + } else { + promise.complete(result); + } + }); + + return promise; + } + +} \ No newline at end of file diff --git a/futur-api/src/main/java/dev/tommyjs/futur/scheduler/Scheduler.java b/futur-api/src/main/java/dev/tommyjs/futur/scheduler/Scheduler.java new file mode 100644 index 0000000..16889f1 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/scheduler/Scheduler.java @@ -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()); + } + }; + } + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/scheduler/Schedulers.java b/futur-api/src/main/java/dev/tommyjs/futur/scheduler/Schedulers.java new file mode 100644 index 0000000..5416e2d --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/scheduler/Schedulers.java @@ -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; + } + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/scheduler/SingleExecutorScheduler.java b/futur-api/src/main/java/dev/tommyjs/futur/scheduler/SingleExecutorScheduler.java new file mode 100644 index 0000000..1c2164d --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/scheduler/SingleExecutorScheduler.java @@ -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()); + } + +} diff --git a/futur-api/src/main/java/dev/tommyjs/futur/trace/ExecutorTrace.java b/futur-api/src/main/java/dev/tommyjs/futur/trace/ExecutorTrace.java new file mode 100644 index 0000000..47d4503 --- /dev/null +++ b/futur-api/src/main/java/dev/tommyjs/futur/trace/ExecutorTrace.java @@ -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")); + } + +} diff --git a/futur-reactive-streams/.gitignore b/futur-reactive-streams/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/futur-reactive-streams/.gitignore @@ -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 \ No newline at end of file diff --git a/futur-reactive-streams/build.gradle.kts b/futur-reactive-streams/build.gradle.kts new file mode 100644 index 0000000..205a74d --- /dev/null +++ b/futur-reactive-streams/build.gradle.kts @@ -0,0 +1,35 @@ +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(project(mapOf("path" to ":futur-api"))) + compileOnly("org.reactivestreams:reactive-streams:1.0.4") + testImplementation(platform("org.junit:junit-bom:5.9.1")) + testImplementation("org.junit.jupiter:junit-jupiter") +} + +tasks { + build { + dependsOn(shadowJar) + } + + withType { + exclude("META-INF/**") + } +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/futur-reactive-streams/src/main/java/dev/tommyjs/futur/reactivestreams/ReactiveTransformer.java b/futur-reactive-streams/src/main/java/dev/tommyjs/futur/reactivestreams/ReactiveTransformer.java new file mode 100644 index 0000000..cdb9129 --- /dev/null +++ b/futur-reactive-streams/src/main/java/dev/tommyjs/futur/reactivestreams/ReactiveTransformer.java @@ -0,0 +1,15 @@ +package dev.tommyjs.futur.reactivestreams; + +import dev.tommyjs.futur.promise.Promise; +import org.jetbrains.annotations.NotNull; +import org.reactivestreams.Publisher; + +public class ReactiveTransformer { + + public static @NotNull Promise wrapPublisher(@NotNull Publisher publisher) { + SingleAccumulatorSubscriber subscriber = SingleAccumulatorSubscriber.create(); + publisher.subscribe(subscriber); + return subscriber.getPromise(); + } + +} diff --git a/futur-reactive-streams/src/main/java/dev/tommyjs/futur/reactivestreams/SingleAccumulatorSubscriber.java b/futur-reactive-streams/src/main/java/dev/tommyjs/futur/reactivestreams/SingleAccumulatorSubscriber.java new file mode 100644 index 0000000..ee752ef --- /dev/null +++ b/futur-reactive-streams/src/main/java/dev/tommyjs/futur/reactivestreams/SingleAccumulatorSubscriber.java @@ -0,0 +1,47 @@ +package dev.tommyjs.futur.reactivestreams; + +import dev.tommyjs.futur.promise.Promise; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +public class SingleAccumulatorSubscriber implements Subscriber { + + private final Promise promise; + + public SingleAccumulatorSubscriber(Promise promise) { + this.promise = promise; + } + + @Override + public void onSubscribe(Subscription s) { + s.request(1); + } + + @Override + public void onNext(T t) { + promise.complete(t); + } + + @Override + public void onError(Throwable t) { + promise.completeExceptionally(t); + } + + @Override + public void onComplete() { + // ignore + } + + public Promise getPromise() { + return promise; + } + + public static SingleAccumulatorSubscriber create(Promise promise) { + return new SingleAccumulatorSubscriber<>(promise); + } + + public static SingleAccumulatorSubscriber create() { + return create(new Promise<>()); + } + +} diff --git a/futur-reactor/.gitignore b/futur-reactor/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/futur-reactor/.gitignore @@ -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 \ No newline at end of file diff --git a/futur-reactor/build.gradle.kts b/futur-reactor/build.gradle.kts new file mode 100644 index 0000000..91dcdbc --- /dev/null +++ b/futur-reactor/build.gradle.kts @@ -0,0 +1,24 @@ +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(project(mapOf("path" to ":futur-api"))) + implementation("io.projectreactor:reactor-core:3.6.0") + implementation(project(mapOf("path" to ":futur-reactive-streams"))) + testImplementation(platform("org.junit:junit-bom:5.9.1")) + testImplementation("org.junit.jupiter:junit-jupiter") +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/futur-reactor/src/main/java/dev/tommyjs/futur/reactor/ReactorTransformer.java b/futur-reactor/src/main/java/dev/tommyjs/futur/reactor/ReactorTransformer.java new file mode 100644 index 0000000..9f6817d --- /dev/null +++ b/futur-reactor/src/main/java/dev/tommyjs/futur/reactor/ReactorTransformer.java @@ -0,0 +1,31 @@ +package dev.tommyjs.futur.reactor; + +import dev.tommyjs.futur.promise.Promise; +import org.jetbrains.annotations.NotNull; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +public class ReactorTransformer { + + public static @NotNull Promise wrapMono(@NotNull Mono mono) { + Promise promise = new Promise<>(); + mono.doOnSuccess(promise::complete).doOnError(promise::completeExceptionally).subscribe(); + return promise; + } + + public static @NotNull Promise<@NotNull List> wrapFlux(@NotNull Flux flux) { + Promise> promise = new Promise<>(); + AtomicReference> out = new AtomicReference<>(new ArrayList<>()); + + flux.doOnNext(out.get()::add).subscribe(); + flux.doOnComplete(() -> promise.complete(out.get())).subscribe(); + flux.doOnError(promise::completeExceptionally).subscribe(); + + return promise; + } + +} diff --git a/futur-standalone/.gitignore b/futur-standalone/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/futur-standalone/.gitignore @@ -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 \ No newline at end of file diff --git a/futur-standalone/build.gradle.kts b/futur-standalone/build.gradle.kts new file mode 100644 index 0000000..05e4a0b --- /dev/null +++ b/futur-standalone/build.gradle.kts @@ -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(project(mapOf("path" to ":futur-api"))) + testImplementation(platform("org.junit:junit-bom:5.9.1")) + testImplementation("org.junit.jupiter:junit-jupiter") +} + +tasks { + build { + dependsOn(shadowJar) + } + + withType { + exclude("META-INF/**") + } +} + +tasks.test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/futur-standalone/src/main/java/dev/tommyjs/futur/standalone/ExclusiveThreadPoolScheduler.java b/futur-standalone/src/main/java/dev/tommyjs/futur/standalone/ExclusiveThreadPoolScheduler.java new file mode 100644 index 0000000..6bb4399 --- /dev/null +++ b/futur-standalone/src/main/java/dev/tommyjs/futur/standalone/ExclusiveThreadPoolScheduler.java @@ -0,0 +1,61 @@ +package dev.tommyjs.futur.standalone; + +import dev.tommyjs.futur.scheduler.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 ExclusiveThreadPoolScheduler implements Scheduler { + + private final ScheduledExecutorService executor; + + protected ExclusiveThreadPoolScheduler(ScheduledExecutorService executor) { + this.executor = executor; + } + + @Override + public void runSync(@NotNull Runnable task, @NotNull ExecutorTrace trace) { + throw new UnsupportedOperationException("Sync task invoked on asynchronous environment"); + } + + @Override + public void runDelayedSync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + throw new UnsupportedOperationException("Sync task invoked on asynchronous environment"); + } + + @Override + public void runRepeatingSync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + throw new UnsupportedOperationException("Sync task invoked on asynchronous environment"); + } + + @Override + public void runAsync(@NotNull Runnable task, @NotNull ExecutorTrace trace) { + executor.submit(wrapExceptions(task, trace)); + } + + @Override + public void runDelayedAsync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + executor.schedule(wrapExceptions(task, trace), delay, unit); + } + + @Override + public void runRepeatingAsync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + executor.scheduleAtFixedRate(wrapExceptions(task, trace), 0L, interval, unit); + } + + public @NotNull ScheduledExecutorService getExecutor() { + return executor; + } + + public static ExclusiveThreadPoolScheduler create(ScheduledExecutorService executor) { + return new ExclusiveThreadPoolScheduler(executor); + } + + public static ExclusiveThreadPoolScheduler create(int nThreads) { + return create(Executors.newScheduledThreadPool(nThreads)); + } + +} diff --git a/futur-standalone/src/main/java/dev/tommyjs/futur/standalone/ThreadPoolScheduler.java b/futur-standalone/src/main/java/dev/tommyjs/futur/standalone/ThreadPoolScheduler.java new file mode 100644 index 0000000..4272c49 --- /dev/null +++ b/futur-standalone/src/main/java/dev/tommyjs/futur/standalone/ThreadPoolScheduler.java @@ -0,0 +1,63 @@ +package dev.tommyjs.futur.standalone; + +import dev.tommyjs.futur.scheduler.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 ThreadPoolScheduler implements Scheduler { + + private final ScheduledExecutorService syncExecutor; + private final ScheduledExecutorService asyncExecutor; + + protected ThreadPoolScheduler(ScheduledExecutorService syncExecutor, ScheduledExecutorService asyncExecutor) { + this.syncExecutor = syncExecutor; + this.asyncExecutor = asyncExecutor; + } + + @Override + public void runSync(@NotNull Runnable task, @NotNull ExecutorTrace trace) { + syncExecutor.submit(wrapExceptions(task, trace)); + } + + @Override + public void runDelayedSync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + syncExecutor.schedule(wrapExceptions(task, trace), delay, unit); + } + + @Override + public void runRepeatingSync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + syncExecutor.scheduleAtFixedRate(wrapExceptions(task, trace), 0L, interval, unit); + } + + @Override + public void runAsync(@NotNull Runnable task, @NotNull ExecutorTrace trace) { + asyncExecutor.submit(wrapExceptions(task, trace)); + } + + @Override + public void runDelayedAsync(@NotNull Runnable task, long delay, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + asyncExecutor.schedule(wrapExceptions(task, trace), delay, unit); + } + + @Override + public void runRepeatingAsync(@NotNull Runnable task, long interval, @NotNull TimeUnit unit, @NotNull ExecutorTrace trace) { + asyncExecutor.scheduleAtFixedRate(wrapExceptions(task, trace), 0L, interval, unit); + } + + public @NotNull ScheduledExecutorService getSyncExecutor() { + return syncExecutor; + } + + public @NotNull ScheduledExecutorService getAsyncExecutor() { + return asyncExecutor; + } + + public static ThreadPoolScheduler create(int nThreads) { + return new ThreadPoolScheduler(Executors.newSingleThreadScheduledExecutor(), Executors.newScheduledThreadPool(nThreads)); + } + +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9230d9d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Nov 19 18:44:26 GMT 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..6881e96 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,5 @@ +rootProject.name = "futur" +include("futur-api") +include("futur-standalone") +include("futur-reactive-streams") +include("futur-reactor") \ No newline at end of file