I had to use the same "CurrentThreadExecutorService" for testing, and although all the solutions offered were good (especially mentioning the Guava path ), I came up with something similar to what Peter Laurie suggested here .
As Axelle Ziegler here mentioned, unfortunately, Peter’s solution doesn’t actually work because of the check introduced in ThreadPoolExecutor in the constructor parameter maximumPoolSize (i.e. maximumPoolSize cannot be <=0 ).
To get around this, I did the following:
private static ExecutorService currentThreadExecutorService() { CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy(); return new ThreadPoolExecutor(0, 1, 0L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), callerRunsPolicy) { @Override public void execute(Runnable command) { callerRunsPolicy.rejectedExecution(command, this); } }; }
fabriziocucci Aug 28 '17 at 10:13 2017-08-28 10:13
source share