Elegantly implementing queue length indicators to ExecutorServices

前端 未结 2 1035
后悔当初
后悔当初 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 01:43

    There is a more direct way:

    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newSingleThreadExecutor();
    // add jobs
    // ...
    int size = executor.getQueue().size();
    

    Although you might consider not to use the convenience create methods of Executor, but rather create the executor directly to get rid of the cast and thus be sure that the executor will always actually be a ThreadPoolExecutor, even if the implementation of Executors.newSingleThreadExecutor would change some day.

    ThreadPoolExecutor executor = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue() );
    

    This is directly copied from Executors.newSingleThreadExecutor in JDK 1.6. The LinkedBlockingQueue that is passed to the constructor is actually the very object that you will get back from getQueue.

提交回复
热议问题