pchiusano
pchiusano

Reputation: 775

How do finalizers interact with a generational GC?

Java's finalize method is called after the JVM determines an object is eligible for garbage collection. There are no real guarantees as to when this will happen, or if it will happen at all before the program exits. My question is whether finalize is guaranteed to be called for objects that are in fact garbage collected. I am specifically thinking about objects in the youngest generation of a generational GC.

In a generational GC, the youngest generation will often be GC'd using a simple mark-sweep collection, where only the live objects are traversed and copied to a new space. Thus, garbage in the youngest generation is not actually traversed. And if the garbage is not traversed, then how do we guarantee that finalize is called for objects that become garbage? It seems that either a) there is no guarantee that finalize will be called for these objects that become garbage in the youngest generation, or b) there is a guarantee that finalize will be called, but objects which override finalize are somehow handled differently.

Upvotes: 2

Views: 175

Answers (2)

Björn Antonsson
Björn Antonsson

Reputation: 1019

This is an article that shows you how one implementation of finalizable objects work http://www.fasterj.com/articles/finalizer1.shtml

Upvotes: 1

Stephen C
Stephen C

Reputation: 718758

My question is whether finalize is guaranteed to be called for objects that are in fact garbage collected.

In practice yes.

The actual guarantee is that the finalize method will be called before the object is finally reclaimed.

And if the garbage is not traversed, then how do we guarantee that finalize is called for objects that become garbage?

The finalize method is not called during traversal (marking). It is called later on objects that didn't get marked in the mark phase. Any object that was marked in the mark phase is reachable ... and not a candidate for reclamation.


The question is, how does the JVM know which objects didn't get marked? This would seem to require a traversal of all the objects in the nursery, even those that are garbage.

That would be one way of doing it.

Another way would be to have a special (non-GC-root) list of "finalizable" list of objects. After the live objects have been evacuated, the list is traversed to examine the old-space copies of all finalizable objects. Any of them that have not been evacuated need to be finalized.

And there may be other schemes too.

If you really, really want to know how it is done, the garbage collector source is freely available.

Upvotes: 1

Related Questions