我们如何在Java中显式调用垃圾回收(GC)?
当不再有对对象的引用时,该对象将被终结,并且当垃圾回收开始时,这些终结的对象将被收集,这将由JVM自动完成。我们可以直接调用垃圾回收,但是不能保证GC将立即开始执行。
我们可以通过两种方式显式调用垃圾 回收
System.gc()方法
Runtime.gc()方法
在java.lang中。Runtime.freeMemory()方法返回Java虚拟机(JVM)中的可用内存量。调用gc() 方法可能会导致freeMemory返回的值增加。
示例
现场演示
public class GarbageCollectionTest {
public static void main(String args[]) {
System.out.println(Runtime.getRuntime().freeMemory());
for (int i=0; i<= 100000; i++) {
Double d = new Double(300);
}
System.out.println(Runtime.getRuntime().freeMemory());
System.gc();
System.out.println(Runtime.getRuntime().freeMemory());
}
}输出结果
15648632 13273472 15970072
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短