When does Java#39;s garbage collection free a memory allocation?(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 的垃圾收集何时释放内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 的垃圾收集何时释放内存分配?


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01