java - GC什么时候开始收集垃圾?

标签 java memory-management memory-leaks

我对垃圾收集器很天真。如果在当前方法执行期间堆内存不足,垃圾收集器是否会等到方法退出?或者它可以在里程碑 1(换句话说,在当前方法执行的中间)启动并释放关键字占用的空间(换句话说,当前方法的局部变量占用的空间)。

public void myMethod() {

//Milestone 1
 List<Keyword> keywords = callSomeFunction();
 keywords = null;
 .
 .
 .
 .
 //Milestone 2

  .
  .
  .

// Milestone 3 - Exit here 

}

最佳答案

简短的回答:垃圾收集器永远不会收集当前正在使用的空间。因此,在您的示例中,只要 keywords 在范围内,就不会收集它引用的任何内容。但是当您将它分配给 null 时,它用来引用的对象可能有资格被收集,如果没有其他人引用它们。这并不意味着这些对象被收集,只是它可能发生。

长答案: 首先,您必须了解 Java 虚拟机有多种实现。 Java 8 虚拟机规范中甚至没有要求 JVM 进行垃圾收集。

也就是说,垃圾收集是 JVM 中的一个常见功能。 Java 语言规范 8 在第 1 章中指出:

The Java programming language ... includes automatic storage management, typically using a garbage collector, to avoid the safety problems of explicit deallocation (as in C's free or C++'s delete).

Java 8 的 JavaDoc 将 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.

然后它继续说 System.gc() 等同于 Runtime.getRuntime().gc()。该方法的 JavaDoc 说:

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.

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.

所以,这里是要点:

  1. 规范不要求垃圾收集
  2. 无论如何,这是 JVM 的通用部分
  3. 您无法真正控制它,您只能“建议”JVM 执行一些垃圾收集
  4. 垃圾收集通常发生在它自己的线程中,只要 JVM 希望它发生,所以它是完全不可预测的

关于java - GC什么时候开始收集垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32128019/

相关文章:

javascript:删除关联数组的所有对象元素

java - GWT 客户端的 YouTube 身份验证

java -\n 从文件读取到列表然后输出时不起作用。 java

c++ - 如何释放结构的内存,每次循环迭代的指针

c# - 托管代码加载时是否需要释放非托管代码中的内存

java - 视觉VM强制GC

java - Android 应用程序无法更改 JAVA 中 HTTP 连接的响应代码

java - 使用抽象方法设计通用API,但在传递给匿名类时必须使用final 变量。有更好的方法来实现这一点吗?

iphone - 保留/复制自动释放的对象

scala - 为什么使用 updateStateByKey 时任务大小一直在增长?