垃圾收集的几个问题
如下的程序有些不懂。
import java.util.*;
class Chair {
static boolean gcrun = false;//the flag wheather garbage machine start run
static boolean f = false;//the flag tell main function to stop create object
static int created = 0;//the flag wheather object contruct
static int finalized = 0;//the flag weather object finalized
int i;//the NO of Object
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!");
}
} ///:~
当程序java Garbage执行时,输出结果为:
Created:47
Beginning to finalize after 4893 Chairs have been created
Finalizing Char #47,Setting flag to stop Chair creation
After all Chairs have been created:
total created=4894,total finalized=4892
bye!
对这个程序,我有以下的理解:
1、垃圾收集器的运行不可知、不可控制。可能在内存分配有可能到了一个很大值时,或可能内存分配出错时,
垃圾收集器就会投入运行。
2、垃圾收集器启动以后,好像所有的内存都会回收,这就有一个问题
垃圾收集器如果在程序即将结束时工作,那么程序在整个运行过程如果有大量的废内存存在,岂不是很影响程序的效率。
另一个问题,当程序占用内存很大时,就有可能就引发了垃圾收集器的运行,如果垃圾收集将所有的内存都回收的话,
那岂不是整个程序都会崩溃。
3、是否只有调用了gc()以后,内存才能令清空。那么岂不是在每个程序结束的时候,都应该gc(),否则不一样会有内存
泄露。
以上几点,还请大家指教。