Finalizer and Reference Types(Strong, Soft, Weak, Phantom..)

Finalizer

Purpose: reclaim unmanaged resources:

Example: FileStream.close -> BufferStream.close -> work to let os release file descriptor(fd).

The fd resource is not managed by the program(not a object in the vm world), so GC will not clean it up.

Note:

Finalizer is for external/unmanaged resources with GC and destructor is for managed resources.

Concern:

  1. Dead lock or bugs can happen if finalizer holds a lock, or worse if reentrant lock is provided and thread scheduled out during object finalization -> undefined behaviour
  2. due to #1, usually finalizatin work is done by dedicated thread
  3. Resurrection: lifecycle of finalizer enabled object A is like:
  4. GC.mark
  5. find A 

  c.queue to a global queue to process after sweep/copy to avoid #1 issues 

  1. run finalizer  ** the A call its finalizer again or other cycle refed object's finalizers -> new strong ref created to itself ::: GOTO step a

In java the spec defines every finalizer will be called only once so #3 can be avoided

 

Reference Types

Reference Type are ordinal in strengths: stronger type of references are collected first(in an earlier pass). Because every type have their purpose and the corresponding actions need to be performed in some order

Strong Ref

Essential requirements by GC. Unreachable denotes (roughly) Dead objects, so help reclaimable objects.

Soft Ref

Under memory pressure objects refed by Soft Ref can be reclaimed(without refed from Strong Ref)

Weak Ref

Used by cache: if one cache works like a global registry and never be reclaimed, of cached object will be immortal without Weak Ref

Finalizer Ref

Interal type of Ref in java, as talked in Finalizer section, to postpone finalizer enabled object to be processed after Sweep/Copy phase

Phantom Ref

TODO: dig out later

roughly to control the reclaim order of objects: like a weak refed obj A with finalizer weak referring another obj B. The Phantom Ref will keep the B alive after A been cleaned up