I need to unit-test some functionality that works across threads, for which I need to guarantee that two jobs are run on different threads.
Using Executors.newCachedThreadPool()
introduces a race-condition, because the test may or may not use the cached thread-pool.
Is there an ExecutorService
that always uses a new thread?
Use a java.util.concurrent.ThreadPoolExecutor
with a corePoolSize
of 0
and a keepAliveTime
of 0
. This will make new tasks spawn a new thread, and threads will be killed immediately after tasks are terminated.
For example:
final ExecutorService executorService = new ThreadPoolExecutor(
0, 2, 0, TimeUnit.SECONDS, new SynchronousQueue<>());
executorService.submit(task1);
executorService.submit(task2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With