Search code examples
javafinalizer

Effective Java - Never depend on a finalizer to update critical persistent state


Why this should not be done? As finalizers will be called when garbage collection is executed, why can't we add persistent related code here?


Solution

  • It says critical(!) persistent data. It is ok to have finalizers who will write away persistent data but it must be ok if this data is not written.

    Since it is not ok to be missing critical data, it should not go into a finalizer.

    But how can a finalizer not be called when the GC has to collect everything? Well for once the application could just be terminated forcefully, thus never leaving a chance for the GC to run.