Reputation: 37095
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?
Upvotes: 7
Views: 2202
Reputation: 1920
As of JDK 19 (preview) you can use Executors.newThreadPerTaskExecutor
.
Upvotes: 6
Reputation: 7406
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);
Upvotes: 16