How to ensure garbage collection of a FutureTask that is submitted to a ThreadPoolExecutor and then cancelled?

前端 未结 4 1824
梦毁少年i
梦毁少年i 2020-12-29 12:53

I am submitting Callable objects to a ThreadPoolExecutor and they seem to be sticking around in memory.

Looking at the heap dump with the M

4条回答
  •  难免孤独
    2020-12-29 13:13

    I couldn't get anything to work so I came up with the following solution. Here is a rough overview: I created an array in the ThreadPoolExecutor that kept track of the runnables that were in the queue. Then when I needed to cancel the queue, I looped through and called a cancel method on each of the runnables. I my case, all of these runnables were a custom class I created and their cancel method simply set a cancelled flag. When the queue brought up the next one to process, in the run of the runnable it would see it was cancelled and skip the actual work.

    So all of the runnables then just get flushed out quickly one by one as it sees it was cancelled.

    Probably not the greatest solution, but it works for me and it doesn't leak memory.

提交回复
热议问题