I'd like to create an Executor
from the "main" thread of a program (similar to the main looper in Android), and then just run until it has processed everything submitted to it:
public class MyApp {
private static Callable<Integer> task = () -> {
// ... return an int somehow ...
};
public static void main(String[] args) throws ExecutionException, InterruptedException {
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));
Thread main = Thread.currentThread();
ExecutorService executorService = Executors.newSingleThreadExecutor(r -> main);
service.submit(task).addListener(() -> {
/// ... do something with the result ...
}, executorService);
executorService.awaitTermination(100, TimeUnit.SECONDS);
}
}
But I get an IllegalThreadState
exception:
SEVERE: RuntimeException while executing runnable MyApp$$Lambda$20/0x00000008000a6440@71f06a3c with executor java.util.concurrent.Executors$FinalizableDelegatedExecutorService@47add263
java.lang.IllegalThreadStateException
at java.base/java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:926)
at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1343)
at java.base/java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:687)
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1137)
at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:957)
at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:726)
at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.afterRanInterruptibly(TrustedListenableFutureTask.java:131)
at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:133)
at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
I could just start an ExecutorService
on a new thread, and then await that, but that seems wasteful.
Is there a good way to create an Executor
from the current thread, and wait for it to process everything that has been submitted to it?