static int i = 1; public RubbishRelease() { System.out.println(i++); } public void finalize() { System.out.println("finalize..."); } public static void main(String[] args) { for (int i = 0; i < 100000; i++) { new RubbishRelease(); new RubbishRelease(); new RubbishRelease(); System.gc(); } System.out.println("over!"); }试试这个~比较下速度,非常明显,所以gc还是不能随便适用嘀~
一种是触发型。这就好比你新new 一个对象,jvm发现eden区(你可以理解为堆中的某块区域)空间不够了。这个时候,jvm就会进行一次minorGC(你可以理解为一种垃圾回收程序)。一种是检查型。比如你虚拟机参数为当老年代(你可以理解为堆中的某块区域)中内存使用率达到了68%的时候就进行一次majorGC(你可以理解为一种垃圾回收程序)。
对于触发型,是不得不gc的。
而对于检查型,相当于一个线程,每隔一段时间就执行某段程序检查看需不需要gc.
而System.gc()。就是建议虚拟机检查一下需不需要gc(也就是上面那个线程,每隔一段时间执行的那个程序).
也就是说本来是30s之后看需不需要gc,而你在此时此刻就让他看需不需要gc.
这是个人猜测,不一定对。
public RubbishRelease() {
System.out.println(i++);
} public void finalize() {
System.out.println("finalize...");
} public static void main(String[] args) {
for (int i = 0; i < 100000; i++) {
new RubbishRelease();
new RubbishRelease();
new RubbishRelease();
System.gc();
}
System.out.println("over!");
}试试这个~比较下速度,非常明显,所以gc还是不能随便适用嘀~