Design of finalization and weak references in VM.

Author:
Salikh Zakirov
Version:
written on 2005-05-31

Object Finalization

As described elsewhere, VM calls function gc_class_prepared() as a mandatory step of class preparation process, in order that GC have a chance to create its own class-specific structure (known as GCVT). During this call, GC can call class_is_finalizable() to find out whether the instances of this class require finalizers to be run. The result is stored in GCVT for later use.

At a later stage, when VM requests an object to be allocated by calling gc_alloc(), or gc_alloc_fast(), GC consults its GCVT to find out whether this class of objects needs to be finalized, and if so, adds the object reference in the finalizable queue, maintained by the GC. Allocation of finalizable objects is guarded from being handled by the inlined fast path by object size overloading hack (see Allocation of objects.). This is needed due to the optimized nature of allocation fast path: fast path assumes that objects don't need any special handling, and we must ensure fast path fails for all object that do require special handling such as finalization.

Later, when the garbage is being collected, GC walks over the finalizable object list and checks if the objects became eligible for finalization (i.e. not reachable otherwise). The GC side of the story is described in more detail in Finalization and weak references design in GC Object chosen for finalization are then "revived" and reported to the VM using vm_finalize_object(). Reviving is performed by marking the object in order to prevent it from being collected before the finalizer has been run. VM places all reported objects to its internal finalization queue and runs the finalizers in a separate thread at a later (unspecified) time. Note, that while running finalization in a dedicated thread is not directly required by the java specification, it is highly desirable in order to improve overall VM robustness, because finalizers may contain user code of arbitrary complexity, including synchronization with other user threads. Thus, running finalizers as a step of garbage collection process while other user threads are suspended will introduce a risk of deadlock and thus must be avoided.

As finalization queue stores direct references to java heap, it is must be handled properly during heap compaction, by adding the locations of the pointers to the list of the slots updated during compaction.

Finalization requirements

The process described above places following requirements

Weak references

See the description of how weak references work in GC: Finalization and weak references design in GC

Genereated on Tue Mar 11 19:25:23 2008 by Doxygen.

(c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable.