Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are immutable objecs loved by JVM's GC?

I know the reason that JVM GC loves short-live object because it can be collected in minor GC. But why does JVM GC love immutable objects?

EDIT: Charlie Hunt says that GC loves immutable objects in his presentation.

Thanks

like image 634
Jacky Avatar asked Jan 07 '13 05:01

Jacky


3 Answers

If the GC can know that an object doesn't contain any references to any gen0 objects, then it can be ignored when performing a gen0 collection. Likewise if an object doesn't contain any reference to any gen0 or gen1 objects, it may be ignored when performing a gen1 collection. The more objects can be ignored during a collection, the faster that collection will be.

If an object survives a gen0 GC, it can be sure that any gen0 object to which it had held a reference will have been promoted to gen1; likewise if an object which didn't contain any gen0 references survives a gen1 GC, any gen1 references it contained will have been promoted to gen2. Thus, once a object has been examined during a gen0 collection, it need not be examined again until the next gen1 collection, unless it is modified. Likewise an object that's examined during a gen1 collection need not be examined until the next gen2 collection unless it is modified.

Knowing whether objects have been modified is a tricky subject, but the key point is that it's very advantageous for the GC if objects haven't been.

like image 81
supercat Avatar answered Oct 19 '22 17:10

supercat


I found the answer from Brian Goetz's article.

In most cases, when a holder object is updated to reference a different object, the new referent is a young object. If we update a MutableHolder by calling setValue(), we have created a situation where an older object references a younger one. On the other hand, by creating a new ImmutableHolder object instead, a younger object is referencing an older one. The latter situation, where most objects point to older objects, is much more gentle on a generational garbage collector. If a MutableHolder that lives in the old generation is mutated, all the objects on the card that contain the MutableHolder must be scanned for old-to-young references at the next minor collection. The use of mutable references for long-lived container objects increases the work done to track old-to-young references at collection time.

like image 41
Jacky Avatar answered Oct 19 '22 16:10

Jacky


Thanks for the link..found it nice :)

From presentation : GC loves small immutable objects and short lived objects.

Edit:

Smaller objects have short memory footprint which means that after collection there will not be much overhead on memory compaction ( Memory compaction is slow for big object as they leave bigger memory holes after they get reclaimed by GC). And short lived objects are also good as they get collected in minor GC cycles.

like image 45
rai.skumar Avatar answered Oct 19 '22 16:10

rai.skumar