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

2023-07-12Java开发问题
15

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

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13