java - 垃圾收集(本地参考)
问题描述
我对 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在继续之前被调用(// 长时间运行的过程)
本地线程会被垃圾收集吗?
或者 GC 会将它们(MyThread 本地引用)标记为活动,因为它拥有对全局引用数据的引用?
解决方案
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.
推荐阅读
- solr - 索引时如何禁用页面提升?
- terraform - 使用 Terraform helm 提供程序的 Helm 图表 - 执行连续图表时出错
- javascript - 我在创建动态表时遇到问题?
- javascript - 将对象数组随机拆分为两个相等的数组
- python - 获取继承函数的 __qualname__
- chatbot - 将 rasa 聊天机器人与 amazon alexa 和 Apple siri 集成
- r - 用 kable 生成表后的新行
- asp.net-core - 在 asp.net 核心中定义参数页面指令时出错
- jenkins - Jenkinsfile 语法:从工作区提交到 Subversion SCM 存储库
- regex - 文件名完全匹配的正则表达式模式