From caafaa203911f9baeaa43db2f1e20082a5fedb2b Mon Sep 17 00:00:00 2001 From: replaceitem <40722305+replaceitem@users.noreply.github.com> Date: Sat, 8 Jan 2022 20:40:20 +0100 Subject: [PATCH] [Scarpet] Task value refactor for better extendability (#1202) --- .../java/carpet/script/value/ThreadValue.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/carpet/script/value/ThreadValue.java b/src/main/java/carpet/script/value/ThreadValue.java index 30c63555..21b2e224 100644 --- a/src/main/java/carpet/script/value/ThreadValue.java +++ b/src/main/java/carpet/script/value/ThreadValue.java @@ -19,18 +19,29 @@ public class ThreadValue extends Value private final long id; private static long sequence = 0L; + public ThreadValue(CompletableFuture taskFuture) + { + this.taskFuture = taskFuture; + this.id = sequence++; + } + public ThreadValue(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) { - id = sequence++; + this(getCompletableFutureFromFunction(pool, function, expr, token, ctx, args)); + Thread.yield(); + } + + public static CompletableFuture getCompletableFutureFromFunction(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) + { ExecutorService executor = ctx.host.getExecutor(pool); if (executor == null) { // app is shutting down - no more threads can be spawned. - taskFuture = CompletableFuture.completedFuture(Value.NULL); + return CompletableFuture.completedFuture(Value.NULL); } else { - taskFuture = CompletableFuture.supplyAsync( + return CompletableFuture.supplyAsync( () -> { try @@ -52,7 +63,6 @@ public class ThreadValue extends Value ctx.host.getExecutor(pool) ); } - Thread.yield(); } @Override