finalize()方法终结条件验证 示例代码

本文探讨了Java中Tank类的实例化与垃圾回收过程,包括如何使用System.gc()强制执行垃圾回收及System.runFinalizersOnExit()方法来确保对象的终结方法被调用。通过示例展示了不同情况下对象终结方法的执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package Initialization;

class Tank{
	int howFull = 0;
	Tank() { this(0);}
	Tank(int fullness){
		howFull = fullness;
	}
	void sayHowFull(){
		if(howFull == 0) 
			System.out.println("Tank is empty!");
		else
			System.out.println("Tank filling status : " + howFull);
	}
	void empty(){
		howFull = 0;
	}
	protected void finalize(){
		if(howFull != 0){
			System.out.println("Error: Tank not empty." + this.howFull);
		}
		//Normally,you'll also do this:
		//Super.finalize(); //call the base-class version
	}
}

public class TankTest {
	public static void main(String[] args) {
		Tank tank1 = new Tank();
		Tank tank2 = new Tank(3);
		Tank tank3 = new Tank(5);
		tank2.empty();
		//Drop the reference,forget to cleanup:
		new Tank(6);
		new Tank(7);
		System.out.println("Check tanks:");
		System.out.println("tank1:");
		tank1.sayHowFull();
		System.out.println("tank2:");
		tank2.sayHowFull();
		System.out.println("tank3");
		tank3.sayHowFull();
		System.out.println("first forced gc()");
		System.gc();
		System.out.println("try deprecated runFinalizerOnExit(true)");
		System.runFinalizersOnExit(true);
		System.out.println("last forced gc():");
		System.gc();
	}
}

 

 

运行结果如下:

 

Check tanks:
tank1:
Tank is empty!
tank2:
Tank is empty!
tank3
Tank filling status : 5
first forced gc()
Error: Tank not empty.7
Error: Tank not empty.6
try deprecated runFinalizerOnExit(true)
last forced gc():
Error: Tank not empty.5

System.runFinalizersOnExit()方法是指当应用程序退出时对所有对象执行终结方法。包括有引用的对象和没有通过引用的对象,而System.gc()垃圾回收方法仅回收那些没有引用指向的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值