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

前端 未结 4 1798
梦毁少年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.

    0 讨论(0)
  • 2020-12-29 13:18

    Refer to: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html

    A Future represents the result of an asynchronous computation. If the result not be retrieved using method get then memory leak happen!

    If you don't want to consume asynchronous result, using Runnable install Callable.

    0 讨论(0)
  • 2020-12-29 13:20

    According to this post, you can call purge on the executor.

    0 讨论(0)
  • 2020-12-29 13:21

    As a work around could you do something like:

    class ClearingCallable<T> implements Callable<T> {
        Callable<T> delegate;
        ClearingCallable(Callable<T> delegate) {
            this.delegate = delegate;
        }
    
        T call() {
            try {
                return delegate.call();
            } finally {
                delegate = null;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题