Search code examples
javamultithreadingspringthreadpoolthreadpoolexecutor

Synchronous Queue fairness policy in ThreadPoolTaskExecutor bean?


I have the following bean

<bean id="executor"
    class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="1" />
    <property name="maxPoolSize" value="1" />
    <!-- Positive value leads to LinkedBlockingQueue,
        any other value leads to SynchronousQueue -->
    <property name="queueCapacity" value="0" />
</bean>

Oracle documentation for SynchronousQueue says the following:

This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order.

My question is: how can I specify that I want order fairness in my bean configuration?

Thanks!


Solution

  • I am not sure why you need a fair synchronous queue and manage the thread access in FIFO order. I had never seen this in real and also not sure if your application will work correctly even if you manage the FIFO.

    But still if you want you can extend the ThreadPoolTaskExecutor and just override the createQueue() like this -

    public class FairThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
        protected BlockingQueue<Runnable> createQueue(int queueCapacity) {
            return (BlockingQueue) (queueCapacity > 0 ? new LinkedBlockingQueue(queueCapacity) : new SynchronousQueue(true));
        }
    }