为什么ArrayList.clear()方法不释放内存? [英] Why ArrayList.clear() method doesn't free memory?

查看:1719
本文介绍了为什么ArrayList.clear()方法不释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找ArrayList.clear()&发现它不会释放内存,而是使该列表为空. 您为什么要等待GC到来?当您可以手动告诉编译器不再需要该特定ArrayList时,释放该内存(它可以通过clear方法本身完成).

为什么要不必要地使GC头痛呢?

我知道System.gc()会影响应用程序的性能,因为它会为整个应用程序运行垃圾回收.

在我的服务器内存有限的情况下,是否有任何方法可以收集此特定的ArrayList垃圾,而不是等待GC救援?列表大小太大.

- 因为我已经初始化了ArrayList(500000)& ;,所以出现了这个问题.假设由于一些预初始化的变量,我的对象大小约为1000bytes,但是由于形成第一个对象本身的某些异常,我需要从该函数返回并释放分配给该ArrayList的内存.我希望我的应用程序可以使用尽可能低的内存. GC对我而言是不得已的选择.

解决方案

您为什么要等待GC来&释放内存(可以用清晰的方法本身完成)

不,它不能. ArrayList确实不再引用对象,但是clear()方法不知道是否仍在其他位置引用它们,因此这就是垃圾收集器的工作.

I was looking into ArrayList.clear() & found that it doesn't free the memory instead made that list null. Why do you want to wait for GC to come & to free that memory (It could have done in clear method itself) when you can tell compiler manually that this particular ArrayList is no longer required.!!

Why do you want to give extra headache to GC Unnecessarily.

I know that System.gc() impacts the application performance since it runs garbage collection for the whole application.

Is there any way out to collect this particular ArrayList garbage instead of waiting GC to come to rescue in case of my server is having limited memory & list sizes are too too big.

Edit:- This problem arises because I have initialized a ArrayList(500000) & lets assume my object size is around 1000bytes due to some pre-initalized variables but due to some exception in forming first object itself I need to return from that function with freeing that memory which I have allocated to that ArrayList.I want my application to consume as low as memory it can. GC is the last resort for me.

解决方案

Why do you want to wait for GC to come & to free that memory (It could have done in clear method itself)

No, it could not. The ArrayList indeed won't be referencing the objects anymore, but the clear() method doesn't know if they are still being referenced somewhere else, so that's why this is a job for the Garbage Collector.

这篇关于为什么ArrayList.clear()方法不释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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