Does the future object returned by executorService.submit(Runnable) hold any reference to the runnable object?

前端 未结 2 814
野的像风
野的像风 2021-02-05 15:34

Let\'s assume we have the following code:

List> runningTasks;
ExecutorService executor;
...
void executeTask(Runnable task){
    runningTas         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 16:31

    1. Does runningTasks( Future ) hold a reference to the task object? --- Yes
    2. How long does it hold it for? Does it still hold it after the task is complete? --- It holds task reference till the task is complete after that it is removed from queue of ThreadPoolExecutor also in FutureTask.finishCompletion() method we set callable(task) reference to null. FutureTask.finishCompletion() is called inside run and cancel methods of FuturetTask. Thus in run and cancel both cases future doesn't have reference to task.
    3. In order to avoid memtory leaks do I havie to take care to remove the future that was added to the list? --- You are safe if you are using Future.

    If you use ScheduledFuture then you may face memory leak issue as ScheduledFuture.cancel() or Future.cancel() in general does not notify its Executor that it has been cancelled and it stays in the Queue until its time for execution has arrived. It's not a big deal for simple Futures but can be a big problem for ScheduledFutures. It can stay there for seconds, minutes, hours, days, weeks, years or almost indefinitely depending on the delays it has been scheduled with.

    For more details with example of memory leak situation and its solution see my other answer.

提交回复
热议问题