Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make executor reject new tasks when another is running?

Using this executor

executor = Executors.newFixedThreadPool(1);

Will run only one task at once, but will execute any subsequent tasks in sequence. I want it to reject new tasks if it is already running one. Should i use another type of executor? Which one? Or should i look for a different approach here?

like image 546
Mateus Viccari Avatar asked Dec 18 '22 12:12

Mateus Viccari


1 Answers

You can do this with a ThreadPoolExecutor with core and maximum pool size of 1.

Finally you need to provide a SynchronousQueue as the queue (although it's not really a queue at all), to make sure that a task is executed only if the single thread is available, otherwise a RejectedExecutionException is thrown.

As a one-liner (the timeout is not applicable in this use case):

new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());

See the other constructors if you wish to handle the rejected tasks in some special way. Especially DiscardPolicy if you don't want even an exception from the rejected tasks.

This also scales up to more than one thread just by increasing the pool sizes. If corepool is less than maxpool, the timeout will again be relevant.

like image 164
Kayaman Avatar answered Jan 18 '23 22:01

Kayaman