ExecutorService, standard way to avoid to task queue getting too full

后端 未结 5 1923
死守一世寂寞
死守一世寂寞 2021-01-31 16:36

I am using ExecutorService for ease of concurrent multithreaded program. Take following code:

while(xxx) {
    ExecutorService exService = Executors         


        
5条回答
  •  名媛妹妹
    2021-01-31 16:40

    The trick is to use a fixed queue size and:

    new ThreadPoolExecutor.CallerRunsPolicy()
    

    I also recommend using Guava's ListeningExecutorService. Here is an example consumer/producer queues.

    private ListeningExecutorService producerExecutorService = MoreExecutors.listeningDecorator(newFixedThreadPoolWithQueueSize(5, 20));
    private ListeningExecutorService consumerExecutorService = MoreExecutors.listeningDecorator(newFixedThreadPoolWithQueueSize(5, 20));
    
    private static ExecutorService newFixedThreadPoolWithQueueSize(int nThreads, int queueSize) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      5000L, TimeUnit.MILLISECONDS,
                                      new ArrayBlockingQueue(queueSize, true), new ThreadPoolExecutor.CallerRunsPolicy());
    }
    

    Anything better and you might want to consider a MQ like RabbitMQ or ActiveMQ as they have QoS technology.

提交回复
热议问题