Tammiexao
Tammiexao

Reputation: 33

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"

I believe this is false because the program should do this automatically, running in the background correct?

Upvotes: 1

Views: 150

Answers (3)

Oliver
Oliver

Reputation: 6250

The method System.gc() does not necessarily call the Garbage Collector. Garbage Collection is dependent on JVM implementation. For Example a Linux JVM may actually call GC when you do System.gc() a Windows JVM may not.

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. 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."

This is one of Java's main advantage the developer need not worry about Memory management and stuff. unlike C++ where you have to do something like

free(obj);

Upvotes: 0

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21728

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. 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. Alternatively you may rethink you algorithm.

These situations are, however, increasingly rare with the newer Java versions; used to be more frequent in the past. The official point of view is never call garbage collector manually.

Upvotes: 0

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). 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.

Upvotes: 4

Related Questions