简体   繁体   English

Java垃圾收集器方法

[英]Java Garbage Collector method

I am trying to understand the garbage collector method . 我正在尝试了解垃圾收集器方法

"In Java, your program must call the garbage collector method frequently; otherwise your program will be overrun with garbage objects" “在Java中,您的程序必须经常调用垃圾收集器方法;否则,程序将被垃圾对象覆盖”

I believe this is false because the program should do this automatically, running in the background correct? 我相信这是错误的,因为程序应该在后台正确运行时自动执行此操作?

Correct. 正确。 In fact, there is no garbage-collector method ( System.gc() is a hint that now might be a good time to garbage collect, but it's nothing more). 事实上, 没有垃圾收集方法( System.gc()是,现在可能是一个好时机,垃圾收集线索,但它没有更多)。 The JVM, if it implements garbage collection (and all Java SE and Java EE ones do), will collect based on its own rules, which usually include concurrently cleaning up short-lived objects, and doing a major collection when memory starts getting low or fragmented. 如果JVM实现垃圾回收(所有Java SE和Java EE都执行垃圾回收),它将根据自己的规则进行收集,通常包括同时清理短期对象,并在内存开始变少或变少时进行大型收集。支离破碎。

While in general calling System.gc() is considered bad, bad, bad, very bad practice, in some cases this may prevent the out of memory error. 虽然通常将System.gc()调用视为不好,不好,不好,非常不好的做法,但在某些情况下,这可以防止内存不足错误。 This is mostly when you allocate lots of objects in a very rapid succession and have time moments when many of these are no longer referenced and can be dropped. 这主要是当您以非常连续的顺序分配许多对象并且有一段时间不再引用这些对象并且可以删除它们时。 While System.gc() is just a hint, sometimes the system may need this hint. 尽管System.gc()只是一个提示,但有时系统可能需要此提示。 Alternatively you may rethink you algorithm. 另外,您可能会重新考虑算法。

These situations are, however, increasingly rare with the newer Java versions; 但是,在较新的Java版本中,这种情况越来越少。 used to be more frequent in the past. 过去更加频繁。 The official point of view is never call garbage collector manually. 官方的观点是永远不要手动调用垃圾收集器。

The method System.gc() does not necessarily call the Garbage Collector. 方法System.gc()不一定调用垃圾回收器。 Garbage Collection is dependent on JVM implementation. 垃圾回收取决于JVM的实现。 For Example a Linux JVM may actually call GC when you do System.gc() a Windows JVM may not. 例如,当您执行System.gc()时,Linux JVM可能实际上会调用GC,而Windows JVM可能不会。

Lets say you have too many unreachable objects in memory but you still have enough Heap space left so the JVM may decide not to run the GC thread. 可以说您的内存中有太多无法访问的对象,但是仍然有足够的堆空间,因此JVM可能会决定不运行GC线程。 So conclusion "There is no guaruntee that the GC thread will run when you call System.gc() and it is not necessary to call it." 因此得出结论: “当您调用System.gc()时,没有保证GC线程将运行,因此不必调用它。”

This is one of Java's main advantage the developer need not worry about Memory management and stuff. 这是Java开发人员不必担心内存管理和内容的主要优势之一。 unlike C++ where you have to do something like 与C ++不同,在C ++中您必须做类似的事情

free(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM