Elegantly implementing queue length indicators to ExecutorServices

前端 未结 2 1033
后悔当初
后悔当初 2021-02-05 01:19

Why, oh why doesn\'t java.util.concurrent provide a queue length indicators for its ExecutorServices? Recently I found myself doing something like thi

2条回答
  •  失恋的感觉
    2021-02-05 02:03

    While you can check the queue size directly. Another way of dealing with a queue that's getting too long is making the internal queue bounded.

    public static
    ExecutorService newFixedThreadPoolWithQueueSize(int nThreads, int queueSize) {
      return new ThreadPoolExecutor(nThreads, nThreads,
                                  5000L, TimeUnit.MILLISECONDS,
                                  new ArrayBlockingQueue(queueSize, true));
    }
    

    This will cause RejectedExecutionExceptions (see this) when you exceed the limit.

    If you want to avoid the exception the calling thread can be hijacked to execute the function. See this SO question for a solution.

    References

    • ThreadPoolExecutor

提交回复
热议问题