views:

928

answers:

3

What happened internally (JVM) when System.gc() or finalize() method called?

Is this really collect garbage or reduce performance ?

+1  A: 

By invoking System.gc() the garbage collector is run (as the name says). At this point when the objects are really being removed the finalize() is called on these objects before they vanish.

The last question shouldn't have an "or" in it. It is garbage collection and reduced performance.

Usually you shouldn't care about gc at all because it does a really good job for you. There are usage scenarios where you want to get rid of a lot of objects at a certain point in time. Than it is feasible.

Norbert Hartl
System.gc() does not necessarily invoke the GC. It is merely a suggestion to the JVM that it is an appropriate time to run the GC, but the final decision to run it is up to the JVM.
coobird
I expect the times that gc is not run if you call System.gc() quite low. On the other hand gc is run fully only if thresholds are reached. By invoking gc() you usually just gc before.
Norbert Hartl
With a single CPU, if you System.gc() and have a lot to clean up, you can see a real performance cliff until cleanup is done. This is can be really painful if you run close to the memory ceiling of your JVM task and it automatically does serious GC on it's own. But if you have multiple CPUs the performance issues are a lot less because GC can happen on the other CPU and the rest of your JVM chugs merrily along...
larson4
Do have links,information or prove for that. I didn't take a look at those things a long time. But if the jvm does not use object space partitions or the like your programme will always be stuck on full gc. A lot of techniques exist to postpone the moment for a full gc as long as possible, e.g. generational gc. They also make the full gc less painfull
Norbert Hartl
+3  A: 

If you want to know garbage collection internals, you should read Hotspot Memory Management Whitepaper from Sun.

cartman
+4  A: 

Exactly what happens when you call System.gc() is JVM dependent. The JVM looks at this call as a suggestion that it might be a good time to run the garbage collector, so don't depend on it.

An object's finalize() method is run on an object by the garbage collector when the JVM determines that there are no more reachable references to that object. You shouldn't call it in your code. Keep in mind that finalize() is not called at the time when your program loses that final reference, but at a future time when the garbage collector is run, so don't depend on it happening at a specific point in time (or at all).

Bill the Lizard