What happens when we explicitly call the Garbage collector method ?
I have come across a method gc()
which starts the garbage collection, how does this work?

- 303
- 2
- 6
- 14
2 Answers
It tells the Garbage collector to do a garbage collection run now.
Note: you can't force the VM into this, but in most circumstances the GC will be run
Here's a link to a blog post on how the Java Garbage Collector works
This question has been asked here
Also have a look at the arguments found here
Update to answer comment: The GC will not collect living objects, even if you're forcing a GC run. It will (mostly) do what it does when run automatically by the JVM
-
Will it collect all the objects in the heap even they are running....? i mean even if there scope it still alive? – Harini Oct 06 '11 at 07:25
-
3@user980918: No, the whole point of garbage collection is that it collects *garbage*, i.e. unreachable objects. The GC should never collect reachable (i.e. live) objects - that would be a serious bug. – sleske Oct 06 '11 at 07:30
-
@sleske True i felt the same..So java has a great feature to find out unused object and clean them.. then why do they have explicit gc() method? – Harini Oct 06 '11 at 07:38
-
@user980918, the gc() is for people who feel the need to call the gc() explicitly. This is generally only useful for certain types of testing. RMI uses it to avoid distributed objects being retained too long. However, you could program Java for 10 years and never find a good use for it. – Peter Lawrey Oct 06 '11 at 07:47
-
@user980918: Good question. There are some (few) situations where explicit control of GC is helpful. However, in general you should not invoke gc() yourself. See the links in the answer for further discussion. – sleske Oct 06 '11 at 07:48
-
@Peter thank you sir. I am new to java so i have some questions which might sound silly for you people.Please don't mind . Thanks once again – Harini Oct 06 '11 at 07:49
-
1@user980918, In my experience; there are no silly questions only silly answers. ;) – Peter Lawrey Oct 06 '11 at 13:03
This method is but a hint to the VM that it could be a suitable time to perform a huge garbage collection. This method could have been useful with the first versions generations of GC when they used to do long pauses, but these times it's quite useless. You're not even guaranteed that there's an actual implementation behind the method :)

- 8,432
- 4
- 28
- 29