java - 孤立岛上的垃圾收集
问题描述
根据我的理解,任何没有引用的对象都有资格进行垃圾收集,即在收集垃圾时应该调用类的 finalize 方法。我在下面有一个类和一个问题,为什么主类中没有引用的线程对象在垃圾收集时没有调用 finalize 方法,如果它调用了。
package com;
class Customer {
int amount = 10000;
synchronized void withdraw(int amount) {
System.out.println("going to withdraw...");
if (this.amount < amount) {
System.out.println("Less balance; waiting for deposit...");
try {
wait(10000);
} catch (Exception e) {
}
}
this.amount -= amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount) {
System.out.println("going to deposit...");
this.amount += amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test {
public static void main(String args[]) throws InstantiationException, IllegalAccessException {
final Customer c = new Customer();
//Island of Isolating a Thread
new Thread() {
public void run() {
// System.out.println("withdraw thread ");
c.withdraw(15000);
}
}.start();
//Island of Isolating another Thread
new Thread() {
public void run() {
// System.out.println("deposit thread ");
c.deposit(10000);
}
}.start();
//attempting to gc manually.
System.gc();
}
//Calling a finialize() method to check whether it is garbage collected or not
protected void finalize() throws Throwable {
System.out.println("Finalize method called");
}
}
编辑:new Thread() {//blah blah }.start(); 是一个被创建的堆的非引用对象。即它没有堆栈引用。理论上,任何非堆栈引用的对象都有资格进行垃圾收集,这实际上适用于垃圾收集。由于它们没有被堆栈引用,因此它也被视为孤立岛。
想知道我在这方面的理解是否错误。谢谢。如果我的想法是矛盾的,请分享您的观点。
解决方案
为什么主类中没有引用的线程对象没有调用finalize
垃圾收集器将活动线程视为活动线程,即使没有其他任何东西引用这些线程。
换句话说,垃圾回收不会使正在运行的代码突然终止。如果是这样,那将是一个非常令人头疼的问题。
最重要的是,您只finalize
在一个从未实例化的类上实现。
推荐阅读
- python - PermissionError: [WinError 5] 访问被拒绝 jupyter 内核
- r - 我在两段代码上得到了不同的结果,我认为这些代码会给出相同的结果
- node.js - “heroku local”找不到模块“load-foreman-procfile”
- html - 字体真棒图标没有出现
- java - 设置列标题的最大高度 - NatTable
- ssl - 我正在尝试使用 PoolingHttpClientConnectionManager 和 ClosableHttpClient 为 HTTPS 创建具有单个连接的连接池并重用它
- razor - SelectListItem 显示类的名称而不是文本字段
- javascript - 模拟点击角度元素
- mongodb - 使用 TypeOrm 连接到 MongoDB Atlas?
- docker - 群清理容器/图像还是我应该运行系统修剪?