问题描述
Java程序员知道JVM运行垃圾收集器,而System.gc()只是JVM运行垃圾收集器的建议。如果我们使用System.gc(),它不一定会立即运行GC。如果我误解了Java的垃圾收集器,请纠正我。除了依赖Java垃圾收集器之外,是否还有其他方式进行内存管理?
如果您打算通过一些有助于管理内存的编程实践来回答问题,请所以。
关于Java内存管理最重要的事情是取消引用。
$ b
只有未被引用的对象才会被垃圾收集。
例如,以下代码中的对象永远不会被收集,您的内存将完全无用。
List objs = new ArrayList();
for(int i = 0; i< Integer.MAX_VALUE; i ++)objs.add(new Object());
但是,如果你不引用这些对象......你可以循环尽可能多的没有内存问题。
List objs = new ArrayList();
for(int i = 0; i< Integer.MAX_VALUE; i ++)new Object();
所以你要做什么,确保你删除对象的引用以不再使用(设置对 null
的引用或清除集合)。
当垃圾收集器运行时,最好由JVM决定。那么除非你的程序要开始使用大量内存并且速度很关键,否则你可能会建议JVM在进入GC之前运行GC,因为你可能会收集垃圾回收和额外的内存。其他方面,我个人认为无需运行 System.gc()
。
希望得到这个帮助。 p>
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.
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.
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();
So what ever you do, make sure you remove reference to object to no longer used (set reference to null
or clear collection).
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()
.
Hope this help.
这篇关于了解Java内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!