Removing all queued tasks of an ThreadPoolExecutor

前端 未结 10 1836
日久生厌
日久生厌 2020-12-03 03:10

i have this rather simple question about the ThreadPoolExecutor. I have the following situation: I have to consume objects from a queue, create the appropiate worker tasks f

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 03:34

    Tell your thread pool to shutdown, getQueue, for-each the result into individual Runnables, remove each Runnable using the remove method. Depending on the type of queue, you might be able to halt the removes early based on return values.

    Basically, this is grabbing the queue and clearing it, only clearing via the methods that work. Instead of manually remembering all the submissions, you use the fact the thread pool already has to remember all the submissions. However, you will probably need to make a defensive copy of the queue, as I think it's a live view, and therefore removing would probably cause a concurrent modification exception if you were iterating/for-eaching over the live view.

提交回复
热议问题