Object Resurrection
   HOME

TheInfoList



OR:

In
object-oriented programming languages Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
with
garbage collection Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclabl ...
, object resurrection is when an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
comes back to life during the process of
object destruction In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implement ...
, 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. In rare circumstances, object resurrection is used to implement certain design patterns, notably an
object pool The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the po ...
, while in other circumstances resurrection is an undesired bug caused by an error in finalizers, and in general resurrection is discouraged.


Process

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 reference Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations. More generally, dangling references and wild references are ...
s and cause errors when used, generally program crash or unpredictable behavior. Instead, in order to maintain
memory safety safety is the state of being protected from various software bugs and security vulnerabilities when dealing with memory access, such as buffer overflows and dangling pointers. For example, Java is said to be memory-safe because its runtime error ...
, 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.


Resurrected objects

A resurrected object may be treated the same as other objects, or may be treated specially. In many languages, notably C#, Java, and Python (from Python 3.4), objects are only finalized once, to avoid the possibility of an object being repeatedly resurrected or even being indestructible; in C# objects with finalizers by default are only finalized once, but can be re-registered for finalization. In other cases resurrected objects are considered errors, notably in Objective-C; or treated identically to other objects, notably in Python prior to Python 3.4. A resurrected object is sometimes called a or zombie, but this term is used for various object states related to object destruction, with usage depending on language and author. A "zombie object" has a specialized meaning in
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, however, which is detailed below. Zombie objects are somewhat analogous to
zombie process On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution (via the exit system call) but still has an entry in the process table: it is a process in the " Terminated state". Thi ...
es, in that they have undergone a termination state change and are close to deallocation, but the details are significantly different.


Variants

In the
.NET Framework The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
, notably C# and VB.NET, "object resurrection" instead refers to the state of an object ''during'' finalization: the object is brought back to life (from being inaccessible), the finalizer is run, and then returned to being inaccessible (and no longer is registered for future finalization). In .NET, which objects need finalization is not tracked object-by-object, but instead is stored in a finalization "queue", so rather than a notion of resurrected objects in the sense of this article, one speaks of objects "queued for finalization". Further, objects can be re-enqueued for finalization via GC.ReRegisterForFinalize, taking care to not multiply enqueue objects.


Mechanism

There are two main ways that an object can resurrect itself or another object: by creating a reference to itself in an object that it can reach (garbage is not reachable, but garbage can reference non-garbage objects), or by creating a reference in the environment (
global variable In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the ''global environment'' or ''global s ...
s, or in some cases
static variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s or variables in a closure). Python examples of both follow, for an object resurrecting itself. It is also possible for an object to resurrect other objects if both are being collected in a given garbage collection cycle, by the same mechanisms. Resurrects itself by creating a reference in an object it can reach: class Clingy: def __init__(self, ref=None) -> None: self.ref = ref def __del__(self): if self.ref: self.ref.ref = self print("Don't leave me!") a = Clingy(Clingy()) # Create a 2-element linked list, # referenced by , a, a.ref.ref = a # Create a cycle a.ref = None # Clearing the reference from the first node # to the second makes the second garbage a.ref = None Resurrects itself by creating a reference in the global environment: c = None class Immortal: def __del__(self): global c c = self print("I'm not dead yet.") c = Immortal() c = None # Clearing , c, makes the object garbage c = None In the above examples, in CPython prior to 3.4, these will run finalizers repeatedly, and the objects will not be garbage-collected, while in CPython 3.4 and later, the finalizers will only be called once, and the objects will be garbage-collected the second time they become unreachable.


Problems

Object resurrection causes a large number of problems. ;Complicates garbage collection :The possibility of object resurrection means that the garbage collector must check for resurrected objects after finalization – even if it does not actually occur – which complicates and slows down garbage collection. ;Indestructible objects :In some circumstances an object may be indestructible: if an object is resurrected in its own finalizer (or a group of objects resurrect each other as a result of their finalizers), and the finalizer is always called when destroying the object, then the object cannot be destroyed and its memory cannot be reclaimed. ;Accidental resurrection and leaks :Thirdly, object resurrection may be unintentional, and the resulting object may be semantic garbage, hence never actually collected, causing a logical
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object ...
. ;Inconsistent state and reinitialization :A resurrected object may be in an inconsistent state, or violate
class invariant In computer programming, specifically object-oriented programming, a class invariant (or type invariant) is an invariant used for constraining objects of a class. Methods of the class should preserve the invariant. The class invariant constrain ...
s, due to the finalizer having been executed and causing an irregular state. Thus resurrected objects generally need to be manually reinitialized. ;Unique finalization or re-finalization :In some languages (such as Java and Python 3.4+) finalization is guaranteed to happen exactly once per object, so resurrected objects will not have their finalizers called; therefore, resurrected objects must execute any necessary cleanup code outside of the finalizer. In some other languages, the programmer can force finalization to be done repeatedly; notably, C# has GC.ReRegisterForFinalize.


Solutions

Languages have adopted several different methods for coping with object resurrection, most commonly by having two-phase garbage collection in the presence of finalizers, to prevent dangling references; and by only finalizing objects once, particularly by marking objects as having been finalized (via a flag), to ensure that objects can be destroyed. Java will not free the object until it has proven that the object is once again unreachable, but will not run the finalizer more than once. In Python, prior to Python 3.4, the standard
CPython CPython is the reference implementation of the Python programming language. Written in C and Python, CPython is the default and most widely used implementation of the Python language. CPython can be defined as both an interpreter and a compi ...
implementation would treat resurrected objects identically to other objects (which had never been finalized), making indestructible objects possible. Further, it would not garbage collect cycles that contained an object with a finalizer, to avoid possible problems with object resurrection. Starting in Python 3.4, behavior is largely the same as Java: objects are only finalized once (being marked as "already finalized"), garbage collection of cycles is in two phases, with the second phase checking for resurrected objects. Objective-C 2.0 will put resurrected objects into a "zombie" state, where they log all messages sent to them, but do nothing else. See also Automatic Reference Counting: Zeroing Weak References for handling of
weak reference In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced ''only'' by weak references – meaning "every chain of ref ...
s. In the .NET Framework, notably C# and VB.NET, object finalization is determined by a finalization "queue", which is checked during object destruction. Objects with a finalizer are placed in this queue on creation, and dequeued when the finalizer is called, but can be manually dequeued (prior to finalization) with SuppressFinalize or re-enqueued with ReRegisterForFinalize. Thus by default objects with finalizers are finalized at most once, but this finalization can be suppressed, or objects can be finalized multiple times if they are resurrected (made accessible again) and then re-enqueued for finalization. Further,
weak reference In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced ''only'' by weak references – meaning "every chain of ref ...
s by default do not track resurrection, meaning a weak reference is not updated if an object is resurrected; these are called short weak references, and weak references that track resurrection are called long weak references.


Applications

Object resurrection is useful to handle an
object pool The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the po ...
of commonly used objects, but it obscures code and makes it more confusing. It should be used only for objects that may be frequently used and where the construction/destruction of it is time-consuming. An example could be an array of random numbers, where a large number of them is created and destroyed in a short time, but where actually only a small number is in use at the same time. With object resurrection, a pooling technique would reduce the unnecessary overhead of creation and destruction. Here, a pool manager would get onto its object stack information in the form of a reference to the object, if it is currently to be destructed. The pool manager will keep the object for reuse later.


See also

* Object lifetime


Notes


References

* * {{refend Memory management Object (computer science)