了解 Java 内存管理 [英] Understanding Java Memory Management

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

问题描述

Java 程序员知道 JVM 运行垃圾收集器,而 System.gc() 只是建议 JVM 运行垃圾收集器.如果我们使用 System.gc(),它不一定会立即运行 GC.

如果我误解了 Java 的垃圾收集器,请纠正我.

Java programmers know that JVM runs a Garbage Collector, and System.gc() would just be a suggestion to JVM to run a Garbage Collector. It is not necessarily that if we use System.gc(), it would immediately run the GC.

Please correct me if I misunderstand Java's Garbage Collector.

除了依赖 Java 的垃圾收集器之外,是否还有其他方式进行内存管理?
如果您打算通过某种有助于管理内存的编程实践来回答这个问题,请这样做.

Is/are there any other way/s doing memory management other than relying on Java's Garbage Collector?
If you intend to answer the question by some sort of programming practice that would help managing the memory, please do so.

推荐答案

关于 Java 内存管理要记住的最重要的事情是nullify";您的参考.

The most important thing to remember about Java memory management is "nullify" your reference.

只有未被引用的对象才会被垃圾回收.

Only objects that are not referenced are to be garbage collected.

例如,以下代码中的对象永远不会被收集,您的内存将被填满而什么也不做.

For example, objects in the following code is never get collected and your memory will be full just to do nothing.

List objs = new ArrayList();
for (int i = 0; i  < Integer.MAX_VALUE; i++) objs.add(new Object());

但是如果你不引用这些对象......你可以随意循环而不会出现内存问题.

But if you don't reference those object ... you can loop as much as you like without memory problem.

List objs = new ArrayList();
for (int i = 0; i  < Integer.MAX_VALUE; i++) new Object();

所以无论您做什么,请确保删除对不再使用的对象的引用(将引用设置为 null 或清除集合).

So what ever you do, make sure you remove reference to object to no longer used (set reference to null or clear collection).

垃圾收集器何时运行最好由 JVM 来决定.好吧,除非您的程序即将开始执行使用大量内存并且对速度至关重要的事情,因此您可能会建议 JVM 在进入之前运行 GC,因为您可能会收集垃圾并继续使用额外的内存.否则,我个人认为没有理由运行 System.gc().

When the garbage collector will run is best left to JVM to decide. Well unless your program is about to start doing things that use a lot of memory and is speed critical so you may suggest JVM to run GC before going in as you may likely get the garbaged collected and extra memory to go on. Other wise, I personally see no reason to run System.gc().

希望这会有所帮助.

这篇关于了解 Java 内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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