Victor
Victor

Reputation: 1345

Java garbage collector and how it knows what objects need to be freed from memory

I've read from multiple sources that a java garbage collector frees the memory of objects that are not being used. My question is how does it know its not being used? Am i correct to say that if i initialized some array, and that array was never referenced used or modified that the space in memory for that variable would be freed?

Thanks

Upvotes: 0

Views: 200

Answers (4)

Nav
Nav

Reputation: 10412

garbage collector uses a non deterministic approach...i.e. you will never know when it will run...you can request for it but never be sure that it will run as soon as you call it...

the example you provided for the array will be cleaned from memory only if there is absolutely no reference at all in your program or it ran out of all the references to itself after executing all of them, but you can't be sure when that memory will be freed...

you can think of the garbage collector as a lazy guy ....but, why blame it ,after all it does all the dirty work of cleaning ;)

Upvotes: 0

Kris
Kris

Reputation: 470

As per specs you can request the GC but can not force it.

In your case the array will be a candidate for GC, when ever the JVM determines that it requires memory it kicks off GC, usually it is when the available memory 15% of the over all memory, this is what I observed on IBM JVM, but not always true.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

The garbage collector only frees memory when it needs to. So there is no guarantee it will ever be freed.

Any object which is not reachable from the Thread stacks via a hard reference can be freed.

Upvotes: 0

Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

then it will be a candidate for garbage collector to be collected. if there is no reference to this object, it will be a candidate. When it will be collected, it depends on the strategy of GC.

Upvotes: 1

Related Questions