Java 的垃圾收集何时释放内存分配?

When does Java#39;s garbage collection free a memory allocation?(Java 的垃圾收集何时释放内存分配?)
本文介绍了Java 的垃圾收集何时释放内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 中创建了一个名为 FOO 的对象.FOO 包含大量数据.. 我不知道说我已经拉入 ram 进行操作的 10 兆字节文本文件.(这只是一个例子)

I have created an object in Java, Named FOO. FOO contains a large amount of data.. I don't know say for a ten mega byte text file that I have pulled into ram for manipulation.(This is just an example)

这显然是一个巨大的空间,我想从内存中释放它.我将 FOO 设置为 NULL.

This is clearly a huge amount of space and I want to deallocate it from memory. I set FOO to NULL.

这会自动释放内存中的空间吗?或者加载的文本文件占用的内存会一直持续到自动垃圾回收吗?

Will this free up that space in memory automatically? or Will the memory taken by the loaded text file be around until automatic garbage collection?

推荐答案

当你将任何对象的引用设置为null时,它就变成可用进行垃圾回收了.在垃圾收集器实际运行之前,它仍会占用内存.除了在抛出 OutOfMemoryException 之前它肯定会运行并从无法访问的对象中回收内存之外,无法保证 GC 何时运行.

When you set the reference of any object to null, it becomes available for garbage collection. It still occupies the memory until the garbage collector actually runs. There are no guarantees regarding when GC will run except that it will definitely run and reclaim memory from unreachable objects before an OutOfMemoryException is thrown.

您可以调用 System.gc() 来请求垃圾回收,但这就是它的本质 - 一个请求.运行由 GC 自行决定.

You can call System.gc() to request garbage collection, however, that's what it is - a request. It is upto GC's discretion to run.

使用 WeakReference 在某些情况下会有所帮助.请参阅 Brian Goetz 的这篇文章.

Using a WeakReference can help in some cases. See this article by Brian Goetz.

这篇关于Java 的垃圾收集何时释放内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)