Java的垃圾收集何时释放内存分配? [英] When does Java's garbage collection free a memory allocation?

查看:140
本文介绍了Java的垃圾收集何时释放内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中创建了一个名为FOO的对象。 FOO包含大量的数据..我不知道是否有一个十兆字节的文本文件,我已经把它拉进了内存操作(这只是一个例子)。

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

这会自动释放内存中的空间吗?

将被加载的文本文件占用的内存大约会自动垃圾收集吗?

解决方案

当您将任何对象的引用设置为 null 时,它将变为可用用于垃圾回收。直到垃圾收集器实际运行,它仍然占用内存。 GC不会保证何时运行,除非在抛出 OutOfMemoryException 之前,它肯定会运行并回收内存。



您可以调用System.gc()来请求垃圾回收,但是,这就是它的要求。这是由GC自行决定的。



使用 WeakReference 可以在某些情况下提供帮助。请参阅Brian Goetz的本文


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)

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?

解决方案

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.

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.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆