Michael Rutherfurd Michael Rutherfurd - 1 month ago 14
Java Question

Is there an ExecutorService that uses the current thread?

What I am after is a compatible way to configure the use of a thread pool or not. Ideally the rest of the code should not be impacted at all. I could use a thread pool with 1 thread but that isn't quite what I want. Any ideas?

ExecutorService es = threads == 0 ? new CurrentThreadExecutor() : Executors.newThreadPoolExecutor(threads);

// es.execute / es.submit / new ExecutorCompletionService(es) etc

Answer Source

Here's a really simple Executor (not ExecutorService, mind you) implementation that only uses the current thread. Stealing this from "Java Concurrency in Practice" (essential reading).

public class CurrentThreadExecutor implements Executor {
    public void execute(Runnable r) {

ExecutorService is a more elaborate interface, but could be handled with the same approach.