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?
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.
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