我正在阅读有关 Java 垃圾收集的文章 here和 here 。我还有两个问题。
假设我有以下类(class)
public final class Employee { private final String empID; private final String empFirstName; private final String empLastName; public Employee(String ID, String Firstname, String Lastname) { this.empID = ID; this.empFirstName = Firstname; this.empLastName = Lastname; } public String getEmpID() { return empID; } public String getEmpFirstName() { return empFirstName; } public String getEmpLastName() { return empLastName; }
然后我将我的员工对象添加到 ArrayList
.
List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee("1", "Sally","Solomon"));
empList.add(new Employee("2", "Harry","Solomon"));
现在,如果我打电话 System.exit(0)
插入最后一个员工对象后,什么时候运行 GC 来释放内存?
- 在提供的其中一个链接中,它讨论了 GC 和静态变量。我对 GC 概念有点陌生,并且有点困惑。该链接说静态变量不会被垃圾收集。使用静态变量时如何释放内存?应用程序关闭时内存会被释放吗?
最佳答案
if I were to call
System.exit(0)
right after the last employee object was inserted, when does the GC run to free up memory?
当 JVM 退出时,它不需要运行自己的垃圾收集器来释放内存。当进程退出时操作系统会回收进程的内存。
这不是 JVM 特有的东西。
How do you free up memory when using static variables?
您可以清空或以其他方式删除对这些静态对象的引用。还有一些其他可能性:Are static fields open for garbage collection?
Will the memory be freed when the application is closed?
是的,但不一定是由 JVM 的 GC 实现的。操作系统会处理它——这是它工作的一部分。
关于java - System.Exit 后的垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39500630/