Skip to content

Commit

Permalink
Execute commands on the same thread they were submitted on
Browse files Browse the repository at this point in the history
* This fixes an issue where Bukkit commands would unexpectedly run off the main thread

Signed-off-by: Ashcon Partovi <[email protected]>
  • Loading branch information
Electroid committed Apr 16, 2020
1 parent 59f112a commit f8a6fbd
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,41 @@

import app.ashcon.intake.argument.CommandArgs;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;

/** Wraps an ExecutorService into a CommandExecutor. */
public class CommandExecutorWrapper implements CommandExecutor {

private final ExecutorService executorService;
private final Executor executor;

public CommandExecutorWrapper(ExecutorService executorService) {
checkNotNull(executorService, "executorService");
this.executorService = executorService;
public CommandExecutorWrapper(Executor executor) {
checkNotNull(executor, "executor");
this.executor = executor;
}

@Override
public <T> Future<T> submit(Callable<T> task, CommandArgs args) {
return executorService.submit(task);
public <T> Future<T> submit(Callable<T> callable, CommandArgs args) {
Task<T> task = new Task<>(callable);
executor.execute(task);
return task;
}

private static class Task<V> extends CompletableFuture<V> implements Runnable {
private final Callable<V> task;

private Task(Callable<V> task) {
this.task = checkNotNull(task, "task");
}

@Override
public void run() {
try {
complete(task.call());
} catch (Throwable t) {
completeExceptionally(t);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* Keeps a mapping of types to bindings and generates commands from classes with appropriate
Expand All @@ -49,7 +48,8 @@ public class ParametricBuilder {
private Authorizer authorizer = new NullAuthorizer();
private CommandCompleter defaultCompleter = new NullCompleter();
private CommandExecutor commandExecutor =
new CommandExecutorWrapper(Executors.newSingleThreadExecutor());
new CommandExecutorWrapper(
Runnable::run); // Runs commands on the same thread they were submitted on

public ParametricBuilder(Injector injector) {
this.injector = injector;
Expand Down

0 comments on commit f8a6fbd

Please sign in to comment.