garbage collection
yjava 2004-03-02 09:06:00 //: c04:Garbage.java
// Demonstration of the garbage
// collector and finalization
class Chair {
static boolean gcrun = false;
static boolean f = false;
static int created = 0;
static int finalized = 0;
int i;
Chair() {
i = ++created;
if(created == 47)
System.out.println("Created 47");
}
public void finalize() {
if(!gcrun) {
// The first time finalize() is called:
gcrun = true;
System.out.println(
"Beginning to finalize after " +
created + " Chairs have been created");
}
if(i == 47) {
System.out.println(
"Finalizing Chair #47, " +
"Setting flag to stop Chair creation");
f = true;
}
finalized++;
if(finalized >= created)
System.out.println(
"All " + finalized + " finalized");
}
}
public class Garbage {
public static void main(String[] args) {
// As long as the flag hasn't been set,
// make Chairs and Strings:
while(!Chair.f) {
new Chair();
new String("To take up space");
}
System.out.println(
"After all Chairs have been created:\n" +
"total created = " + Chair.created +
", total finalized = " + Chair.finalized);
// Optional arguments force garbage
// collection & finalization:
if(args.length > 0) {
if(args[0].equals("gc") ||
args[0].equals("all")) {
System.out.println("gc():");
System.gc();
}
if(args[0].equals("finalize") ||
args[0].equals("all")) {
System.out.println("runFinalization():");
System.runFinalization();
}
}
System.out.println("bye!");
}
} ///:~
这是TIJ上的一道关于垃圾清理的例题,有以下几个小问题不明白,请大家指点:
finalized++;在finalize()中到底起什么作用,是清理一个对象累加一次吗?
运行程序时没有命令行参数也能把对象都清理完。在我的机子上结果是这样的:
Created 47
Beginning to finalize after 3496 Chairs have been created
Finalizing Chair #47, Setting flag to stop Chair creation
All 3496 finalized
After all Chairs have been created:
total created = 3497, total finalized = 3496
bye!
命令行参数是gc时:
Created 47
Beginning to finalize after 3495 Chairs have been
Finalizing Chair #47, Setting flag to stop Chair c
All 3495 finalized
After all Chairs have been created:
total created = 3496, total finalized = 3495
gc():
All 3496 finalized
bye!
命令行参数是finalize时:
Created 47
Beginning to finalize after 3495 Chairs have been created
Finalizing Chair #47, Setting flag to stop Chair creation
All 3495 finalized
After all Chairs have been created:
total created = 3495, total finalized = 3495
runFinalization():
bye!
为什么没有All 3495 finalized呢?finalized >= created啊!
如果自己不写finalize(),垃圾清理怎么进行?