publicclassMyTest1{publicstaticvoidmain(String[] args){
List<MyTest1> list =newArrayList<>();for(;;){
list.add(newMyTest1());
System.gc();//显式垃圾回收!}}}
OutOfMemoryError:
Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. OutOfMemoryError objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.
当Java虚拟机由于内存不足而无法分配对象,并且垃圾回收器无法提供更多内存时引发。虚拟机可以构造OutOfMemoryError对象,就好像禁用了抑制和/或堆栈跟踪不可写一样。
publicclassOutOfMemoryErrorextendsVirtualMachineError{//OutOfMemoryError 继承了 VirtualMachineError}
System.gc():
Runs the garbage collector.
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
调用gc方法意味着Java虚拟机将花费精力回收未使用的对象,以便使它们当前占用的内存可用于快速重用。当方法调用返回控件时,Java虚拟机已尽最大努力从所有丢弃的对象中回收空间。
The call System.gc() is effectively equivalent to the call:
Runtime.getRuntime().gc()publicstaticvoidgc(){
Runtime.getRuntime().gc();}
Runtime.getRuntime().gc():
Runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects.
调用gc方法意味着Java虚拟机将花费精力回收未使用的对象,以便使它们当前占用的内存可用于快速重用。当方法调用返回控件时,Java虚拟机已尽最大努力从所有丢弃的对象中回收空间。
The name gc stands for"garbage collector". The virtual machine performs this recycling process automatically as needed, in a separate thread, even if the gc method is not invoked explicitly.
gc这个名字代表“垃圾收集器”。虚拟机根据需要在单独的线程中自动执行此回收过程,即使未显式调用gc方法也是如此。
The method System.gc() is the conventional and convenient means of invoking this method.
方法System.gc()是调用此方法的常规且方便的方法。
publicnativevoidgc();
实战jvisualvm查看堆的情况:实例:public class MyTest1 { public static void main(String[] args) { List<MyTest1> list = new ArrayList<>(); for (; ;) { list.add(new MyTest1()); System.gc(); //显式垃圾回收! }