如何在Java中释放内存? [英] How to free memory in Java?

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

问题描述

有没有办法在Java中释放内存,类似于C的 free()函数?或者将对象设置为null,并依赖于GC唯一的选项?

解决方案

Java使用托管内存,可以通过使用 new 运算符来分配内存,并且可以取消分配内存的唯一方法是依靠垃圾回收器。



内存管理白皮书(PDF)可以帮助解释发生了什么。

您也可以调用 System.gc()来建议垃圾收集器立即运行。但是,Java Runtime会做出最终决定,而不是您的代码。



根据 Java文档


<调用gc方法表明
Java虚拟机会花费
来回收
中的未使用对象,以便使它们的内存
当前占用可用于快​​速
重用。当控制从
方法调用返回时,Java虚拟机
已尽最大努力从所有被丢弃的对象中回收
空间。



Is there a way to free memory in Java, similar to C's free() function? Or is setting the object to null and relying on GC the only option?

解决方案

Java uses managed memory, so the only way you can allocate memory is by using the new operator, and the only way you can deallocate memory is by relying on the garbage collector.

This memory management whitepaper (PDF) may help explain what's going on.

You can also call System.gc() to suggest that the garbage collector run immediately. However, the Java Runtime makes the final decision, not your code.

According to the Java documentation,

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

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

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