何时将Callable传递给可用于垃圾回收的ExecutorService

时间:2017-03-29 18:48:17

标签: java multithreading garbage-collection executorservice callable

我有一个8的线程池,我给它大约100个实现Callable的类实例,即WorkerThread

for (List<String> s : listOfLists) {
    Future<?> future = executor.submit(new Worker(hugeList));   
}

for (Future<?> f : futures) {
        try {
            String result = (String) f.get();
        } catch (InterruptedException e) {
            logger.error("Interrupted", e);
        } catch (ExecutionException e) {
            logger.error("Execution exception", e);
        }
    }


            executor.shutdown();

传递给执行程序的实例何时才有资格进行垃圾回收?执行f.get()后,它们就有资格进行垃圾回收,或者所有new Worker(hugeList)都将保留在内存中,直到调用executor.shutdown()为止。

每个new Worker()都非常大,我会在各自的线程执行后进行垃圾回收。但我不确定他们什么时候有资格参加。

1 个答案:

答案 0 :(得分:1)

除非callable的结果引用了callable本身,否则只要执行任务,它就不会被任何引用,因此符合GC的条件。

池是一个队列,其中任务等待执行,以及一组线程将它们从队列中取出并执行它们。一旦执行,池就不再关心任务了,也不会将它们放在任何地方。