System.gc
Im a bit confused about the usage of System.gc(). Now System.gc() does not guarantee that the garbage collection would start immediately. However iv observed that at times System.gc() does invoke the garbage collection almost immediately.
My question is that when we say System.gc(), how does JVM decide weather to start garbage collection or not
It doesn't matter. How it does it varies from JVM to JVM, and the point is, you should never rely on calling System.gc() to work
System.gc() <=> "hey, JVM, sorry to intrude in your algorithm, but...if you're not too busy right now (i.e., not executing a bunch of higher priority threads ), could you run gc for me?".
>> System.gc() <=> "hey, JVM, sorry to intrude in your algorithm, but...if >> you're not too busy right now (i.e., not executing a bunch of higher
>> priority threads ), could you run gc for me?".
But isnt this how JVM works normally too? i.e do the garbage collection when there are no higher priority threads available.. so what difference does calling a System.gc make
> >> System.gc() <=> "hey, JVM, sorry to intrude in
> your algorithm, but...if >> you're not too busy right
> now (i.e., not executing a bunch of higher
> >> priority threads ), could you run gc for me?".
>
> But isnt this how JVM works normally too? i.e do the
> garbage collection when there are no higher priority
> threads available.. so what difference does calling a
> System.gc make
Maybe no difference at all. Who knows? No point relying on it though
> But isnt this how JVM works normally too? i.e do the
> garbage collection when there are no higher priority
> threads available.. so what difference does calling a
> System.gc make
Possibly none, which is what he was trying to say. Otherwise, it could slow things down because you could end up GCing when it's not necessary. It might also improve a little, if you know that you won't have time to clean up later and have a big mess right now.
And it all might change again with the next release. Or JVM implementation.
> >> System.gc() <=> "hey, JVM, sorry to intrude in
> your algorithm, but...if >> you're not too busy right
> now (i.e., not executing a bunch of higher
> >> priority threads ), could you run gc for me?".
>
> But isnt this how JVM works normally too? i.e do the
> garbage collection when there are no higher priority
> threads available.. so what difference does calling a
> System.gc make
Not much.
With a System.gc() call, the JVM might run gc right away if it's not busy doing more important things, and was planning to call gc itself a bit later on.
So you might have anticipated the point in the algorithm where the gc call is made.
Or it might run gc when there was not really a need to (plenty of memory left), but it wasn't busy anyway.