Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an ExecutorService that creates a new thread for every task?

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?

like image 898
sdgfsdh Avatar asked Jul 06 '17 13:07

sdgfsdh


1 Answers

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);
like image 183
dcsohl Avatar answered Sep 18 '22 15:09

dcsohl