In object-oriented programming languages with garbage collection, object resurrection is when an object comes back to life during the process of object destruction, as a side effect of a finalizer being executed.
Object resurrection causes a number of problems, particularly that the possibility of object resurrection – even if it does not occur – makes garbage collection significantly more complicated and slower, and is a major reason that finalizers are discouraged. Languages deal with object resurrection in various ways, as solutions to these problems. In rare circumstances, object resurrection is used to implement certain design patterns, notably an object pool, while in other circumstances resurrection is an undesired bug caused by an error in finalizers, and in general resurrection is discouraged.
Object resurrection occurs via the following process. First, an object becomes garbage when it is no longer reachable from the program, and may be collected (destroyed and deallocated). Then, during object destruction, before the garbage collector deallocates the object, a finalizer method may be run, which may in turn make that object or another garbage object (reachable from the object with a finalizer) reachable again by creating references to it, as a finalizer may contain arbitrary code. If this happens, the referenced object – which is not necessarily the finalized object – is no longer garbage, and cannot be deallocated, as otherwise the references to it would become dangling references and cause errors when used, generally program crash or unpredictable behavior. Instead, in order to maintain memory safety, the object is returned to life or resurrected.
In order to detect this, a garbage collector will generally do two-phase collection in the presence of finalizers: first finalize any garbage that has a finalizer, and then re-check all garbage (or all garbage reachable from the objects with finalizers), in case the finalizers have resurrected some garbage. This adds overhead and delays memory reclamation.