I need to to know whether the Garbage Collector in Java works on its own or we do need to start it.
It works on its own. You can "suggest" that it run, but that's about it.
Yes, garbage collection is automatically handelled by Java.
When an object is no longer referred to by any variable, Java automatically reclaims memory used by that object. This is known as garbage collection.
Still the method
System.gc()
method may be used to call it explicitly.
The GC is a deamon thread that's started with your JVM and ends when your JVM ends (JVM is stoped if no more non-deamon threads exist).
It runs in background and kicks into action when/if needed. The JVM decides when it runs and you can "request" it to run with System.gc().
But I should mention that you must not write your code to depend on the GC to run (finalizers in Java are not like destructors in C++). People tend to count to much on the GC and then forget about it which is a no-no and leads to memory leaks and hard to find bugs.
What you can count on is that before you get a java.lang.OutOfMemoryError, the GC kiked into action and did its best.
It works on its own according to an optimized algorithm to get the optimal performance. You can perform a force garbage collection but it is not recommended because it can block the normal Garbage collection pattern reducing the actual performance.
You should read this Old SO Discussion on a related topic.
(This is probably just repeating what other answers were trying to say ... However, it is worth saying this clearly.)
The Java garbage collector runs automatically as required, and there is no need to start it.
There is a static method (System.gc()
) that an application can call to request that the garbage collector run "now". However:
- The JVM can be configured to pay no attention to this request.
- It is generally a bad idea to make this request because it can significantly degrade garbage collector performance. Generally speaking, the best time to run the garbage collector is when there is lots of garbage to be collected, and only the JVM knows when that is likely to be.
EDIT - the cure for large garbage collection latencies is to change the JVM's garbage collector properties to select the low latency collector. Calling System.gc()
is not the way to deal with this in a modern JVM.
The only occasion I know of where you have to call System.gc() is when you are creating lots of Direct ByteBuffers. For heap memory, an OutOfMemoryError will only occur after a Full GC, however for direct memory, if you run out (even though there might be buffers which are not referenced), no GC is called and so you might have to call it yourself before trying again.
I would hope this is something which is fixed in future versions of Java.