如何在 Java 中释放内存?

How to free memory in Java?(如何在 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 中释放内存?

基础教程推荐