How to free memory in Java?(如何在 Java 中释放内存?)
问题描述
有没有办法在 Java 中释放内存,类似于 C 的 free() 函数?还是将对象设置为 null 并依赖 GC 是唯一的选择?
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 使用托管内存,因此分配内存的唯一方法是使用 new 运算符,并且唯一的方法是释放内存依赖于垃圾收集器.
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.
本内存管理白皮书 (PDF) 可能帮助解释发生了什么.
This memory management whitepaper (PDF) may help explain what's going on.
您也可以调用 System.gc() 来建议垃圾收集器立即运行.但是,Java 运行时做出最终决定,而不是您的代码.
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.
根据 Java 文档,
调用 gc 方法表明Java 虚拟机花费精力朝着回收未使用的对象为了让他们的记忆目前占用可用于快速重用.当控制权从方法调用,Java 虚拟机已尽最大努力收回所有丢弃的对象的空间.
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 中释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中释放内存?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
