问题描述
我在 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 的垃圾收集何时释放内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!