首页 > 解决方案 > 垃圾收集(本地参考)

问题描述

我对 GC 在 Java 中的工作方式感到困惑。

以下是让我感到困惑的代码片段:

private Data data = new Data();

void main() {

    for (int i = 0; i < 100 ; i++) {
       MyThread thread = new MyThread(data);
       thread.start();
    }

    System.gc();

    // Long running process

} 

class MyThread extends Thread {
    private Data dataReference;

    MyThread(Data data) {
        dataReference = data;
    }
}

在上面的例子中,如果gc在继续之前被调用(// 长时间运行的过程)

标签: javaandroidgarbage-collectionjvm

解决方案


The MyThread instances may be garbage collected only after they are done (i.e. their run method is done). After the for loop ends, any instances of MyThread whose run method is done may be garbage collected (since there are no references to them).

The fact the the MyThread instances each hold a reference to a Data instance that doesn't get garbage collected doesn't affect the time the MyThread instances become eligible for garbage collection.


推荐阅读