# Bezpieczna dealokacja obiektów

(różn.) ← poprzednia wersja | przejdź do aktualnej wersji (różn.) | następna wersja → (różn.)
Skocz do: nawigacji, wyszukiwania

This paper appears 30 years after the article by G.Cioni and A. Kreczmar under the same title . We 1 explain the problems of managing objects, 2 compare with existing (partial!) solutions and finally, 3 present a specification of Kreczmar’s system as an axiomatic system.

programming languages objects garbage collection dangling reference safety

# Managing objects

Proper management of objects plays an essential role in execution of object-oriented programs. It must ensure safety and efficiency. Ill thought ways to remove objects appear unsafe. On the other hand keeping not needed objects slows down the calculations and may lead to a blockade.

In 1984 Antoni Kreczmar and Gianna Cioni presented an object management system which is free of dangling references and is efficient. The system has been validated by the use in Loglan’s running system (i.e. virtual machine).

Most of presently used object oriented programming languages appeared after that date (C++ in 1985, Java in 1995, Python in 1989, Ruby 1993). No one of them has a system similar to the Kreczmar’s one. In C++ deallocation of objects is allowed without any form of control. It is well known that the system has no protection against dangling reference errors.

Java programming language forbids the explicit removal of objects. Its system is safe however inefficient.

We think that it is worthwhile to discover the solutions contained in and to apply them in practice.

Let us expose briefly the problems. Objects are created, used and eventually become not needed anymore.

The designer of an object management system is confronted to three major threats:

• memory leak problem,
• memory fragmentation,
• dangling references problem.

Memory leak occurs when objects are created and remain unused. Program consumes memory. It leads to the slowdown of computations or even to a complete blockade.

There exists a variety of object management systems. One may classify them with respect to different definitions of garbage.

The first, most natural, definition of garbage reads “Object is a garbage whenever the program decides it is no longer needed”. This definition is accepted in C++ programming language. A programmer has the instruction delete(x) to his disposal. However, the instruction has a side effect: the dangling reference may appear. Namely, we observe some variables that point to segments of memory where no object resides. A dangling reference provokes another error of contradicting information. This phenomenon occurs when two variables point to the same address and one says: “I am pointing to an object of type A” and the other says “I am pointing to an object of type B”. Errors of both kinds are difficult in diagnosis and very dangerous ones.

Another definition of garbage reads: “Object with no references to it is a garbage”. Some programming languages try to keep track of references with reference counters (e.g. Python ). In this way a garbage collector can easily identify objects with reference counters equal zero as garbage. However, by introducing reference counters one creates an overhead in code’s length and also in execution time. The result is a slowdown of execution (A. Appel says “On the whole, the problems with reference counting outweigh its advantages”, p.264).

Subsequent definitions of garbage bases on different types of references. Namely, one differentiates weak references from normal ones. Now, “Object $o$ is an garbage if there is no normal reference to it, even if there exist weak reference to $o$”. The weak references were introduced with two aims: 1to decrease the cost of reference counting, 2to diminish the risk that some objects will be kept for the programmer forgot to nullify all references to it.

All three types of object management systems have certain deficiencies. The question arises: is it possible to replace operation delete by another operation kill, such that kill has no side effect of dangling reference. In the paper of Cioni and Kreczmar it was shown that there exists an objects management system with kill operation.

Any program that intensively creates objects and deallocates some, may cause fragmentation of the object memory. Sometimes, the situation may be improved by the defragmentation.[1]

The system described by Kreczmar is a hybrid one. For it allows to

• deallocate no longer needed objects (by means of kill operation),
• compactify heap of object (a defragmentation operation),
• garbage collect objects that are not accessible (by a reference).

Below we compare object programming languages we require that any system that manages heap of objects should satisfy the following conditions:

1. For every type (class) $T$, for every variable $x$. If the variable $x$ is of type $T$ then its value is an object of a subclass $U$ of class $T$ or $x=none$. (This is a global invariant of the system)
2. For every object $s$ it is possible to distinguish the fields containing pointers to objects from the fields that hold values of primitive types, like e.g. integer, float, boolean,...

# Deallocation in Java, C++, Python et al.

In this section we briefly present the solutions taken in other object oriented languages.

## C++, object Pascal, Objective C

We shall limit our considerations to the programs free of malloc instruction. For malloc instructions break the rules r1, r2, listed above.

Object $x$ can be deleted with $delete(x)$ statement. Other variables that are pointing to the removed object preserve their value. It leads to the dangling references error. The error can be avoided if all those variables are nullified $x1 = null; ... xn=null;$.

It is to a developer to remember all variables referring to the object getting deallocated and to nullify all of them prior to instruction delete. Obviously it is an error prone approach. To decrease the number of errors the notion of weak reference was proposed. .

## Java, Python

Already the report of language Modula3 drew attention to the risk of hanging references and non-existence of an algorithm that could detect such errors. In Java white paper there are quite a few statements describing this problem and justifying the interdict of $delete$ instruction. Instead there is a Garbage Collector mechanism, which frees developer from manual removing of references to objects.

Soon, the opinion that garbage collector is an ultimate solution in objects management was verified. Three years after first version of Java (1995), in JDK 1.2 weak references have been introduced. Developer can declare variable as weak reference. Weak references do not change reference counter in cPython , and garbage collection algorithm does not take them into account in Java. If there are no strong references to object it is considered for collection. Even if there are some weak references to it.

## Comparison

l p3cmp3cmp3cm &

Loglan’82

&

C++

&

Java, Python

Pre- &

Code &

kill($x_i$)

&

delete($x_i$)

&

$\hspace*{1cm}x_1=null;\newline\hspace*{1cm}x_2=null;\newline\hspace*{1cm}...\newline\hspace*{1cm}x_n=null$; Now, the instruction

$gc()$the object $o$ will be deleted.

Post- & All the variables took the value none.Object $o$ is deleted. & Object $o$ has been deleted. The variable $x_i$ has the value null. Other variables point to the deleted frame – it is a dangerous error – dangling reference. & Object $o$ has been deleted – under condition that all the references to the object have been earlier assigned the null value. .

Cost &

$O(1)$

&

$O(1)$

& $O(n+m)$$m$ is the global size of the heap of objects.

Risk &

No risk(!)

For each attempt to read and/or write from the deleted object will raise an error signal {reference to none}. & High probability of dangling reference error. High probability of the error of contradicting information. & Chances that programmer will forget to nullify some reference to the object $o$ and hence that the object will remain not deleted.

Observation. Lets consider situation from Java:

$x_1:x_1 \rightarrow o$

$y_{weak} \stackrel{weak}{:=} x_1$

If weak reference $y$ refer to some object o, then there exists a strong reference $x_i$ to same object:

$y_{weak}: y_{weak} \rightarrow o \Leftrightarrow exists\ x_i \rightarrow o$

It is only partially true. We could say probably true. Due to non-deterministic behaviour of garbage collector new ambiguity arises. After operation $x_1:=null$ weak reference $y_{weak}$ continues to refer to original object $o$ for some time. Only after run of garbage collection mechanism object is disposed and weak reference is nullified. Due to non-deterministic implementations of most garbage collectors developers cannot predict or effectively enforce collection. Side effect of this property is a necessity to treat normal object references and weak references in different manner.

Second observation. As long as weak reference to the object exists we can provoke a situation when object intended for collection will be restored to life:

123456789= Disposable tg = new Disposable();
/* A new Disposable object o created, tg is a reference to the object o */
WeakReference<Disposable> weak_tg = new WeakReference<Disposable>(tg);
/* creates Weak Reference to the same object o */
tg = null; /* remove last reference to the object o
The object o is ready to be collected */
System.gc(); /* This is a hint to activate GC */
Disposable tg2 = weak_tg.get();
/* It may happen that GC was not activated
And operation get will return reference to the object o */

This will happen when instruction $System.gc()$ will be ignored for some reason by virtual machine.

# Algorithmic specification of Kreczmar’s system

System for the first time presented in original article is part of running-system (virtual machine) Loglan’82 language. Last 30 years provided us with arguments to renew interest in Kreczmar’s system. In this chapter we will provide formal requirements for managing memory of objects. We used here H.Oktaba thesis . After reading these requirements, the reader can better understand the nature of the result .

## Informal description

The universe of a heap managing system HM consists of states and objects. A state may be viewed as a finite set of objects. For the purpose of the present work we can abstract from the structure of objects, even from their size.[2]

The universe of HM system consist of two sets $U = Frames \cup States$ with the following operations:

• $reserve: States \rightarrow Frames$
• $insert: Frames \times States \rightarrow States$
• $delete: Frames \times States \rightarrow States$
• $member: Frames \times States \rightarrow {true, false}$
• $initSt \in States$
• $kill: Frame \times States \rightarrow States$

$States$ are finite sets of $frames$. For each state $s$ function $reserve$ returns a frame that does not belong to $s$. For each pair $\langle e, s \rangle$ operation insert return the set-theoretical union of the set $s$ and and the element $e$. Similarly, operation delete returns the set $s'$ that resulted by the deletion of element $e$ from the set $s$. The element $initSt$ is the empty set.

## Algorithmic specification

Specifications can be expressed in two variants:

• a metamathematical one, or
• a quasi-programmed one.

We choose the second notation. Its form is similar to Java’s interface or ADA’s specification. The differentia specifica stems from the presence of algorithmic formulas.[3] They are invariants or axioms of the specified class.

Remember, in this way we define a formalized language in which one may program algorithms and/or write formulas.

123456789012345678= unit HeapManagement: class;
unit Frame: class ; ...
unit State: class ...
unit reserve: function(s: State): Frame ...
unit member: function(f:Frame, s:State): Frame ...
unit insert: function(f:Frame,s: State): State; ...
unit delete: function(f:Frame, s: State): State ...
unit kill: function(f:Frame, s: State): State ...
unit amb: function(s: State): Frame ...
unit initState: function(): State ...

(* —– Invariants (i.e. axioms) of the Heap Management system —– *)

Below we shall use abbreviations: $F$r instead of Frames, $St$ instead of States,
res – reserve, $mb$ – member, $ins$ – insert, $del$ – delete, $init$ – initstate.

1. $\forall_{s \in St}\ \textbf{while}\ s \neq init \ \textbf{do}\ s := del(amb(s),s) \ \textbf{od}\ (s = init)$

Every state is a finite set of frames

2. $\forall_{f \in Fr}\ \lnot mb(f, init)$

initstate is the empty set of frames

3. $\forall_{s \in St} \ \lnot mb(none, s)$

none does not belong to any state

4. $\forall_{s \in St} \ \lnot mb(res(s),s) \wedge res(s) \neq none$

for every state $s$, function $res$ returns a frame that does not belong to state $s$

5. $\forall_{s \in St} \ s\neq init \Rightarrow mb(amb(s),s)$

For every non-empty state, function $amb$ returns a member of the set $s$

6. $\{s':=ins(f,s)\}(mb(f,s')\wedge \forall_{f' \in Fr}(mb(f',s) \Leftrightarrow mb(f',s'))$

operation insert adds frame f to the set s

7. $\{s':=del(f,s) \}(\lnot mb(f,s')\wedge \forall_{f' \in Fr}(mb(f',s)\Leftrightarrow mb(f',s'))$

operation del deletes frame f from the set s

8. $mb(f,s) \Leftrightarrow \left \{ \begin{array}{l} \textbf{begin} \\ \quad s1 := s;\ bool := false; \\ \quad \textbf{while} \ s1 \neq init \wedge \lnot bool \\ \quad \textbf{do} \\ \qquad f1 := amb(s1); \\ \qquad \textbf{if} \ f=f1 \ \textbf{then} \ bool := true \ \textbf{fi}; \\ \qquad s1 :=del(f1,s1); \\ \quad \textbf{od} \\ \textbf{end} \ \end{array} \right \} bool$

This formula defines the relation member, its implementation may differ however. We require that its cost should be constant.

9. The operation kill is described by a scheme. The index $k$ may be any natural number $k\gt0$, let $1 \leq i \leq k$

This is a scheme, it tells that operation kill in one move nullifies all the references to the object pointed by the variable $f_i$. We require that its cost should be constant.

end HeapManagement;

## Properties of the specification

The above set of algorithmic formulas defines the requirements imposed on a class to be implemented. Moreover, it allows to prove some useful facts e.g.

For every state s,
$\forall_{s \in State}\, \left \{ \begin{array}{l} \textbf{begin} \\ \quad s' := initSt; \\ \quad \textbf{while}\ s \neq initSt\ \textbf{do} \\ \qquad r := reserve(s'); \\ \qquad \textbf{if}\ member(r,s)\ \textbf{then} \ s := delete(r,s) \ \textbf{fi}; \\ \qquad s' := insert(r,s') \\ \quad \textbf{od} \\ \textbf{end} \end{array} \right \}\, (s = initSt)$

i.e. the operation reserve new frame may replace the operation amb in the postulate that every state is a finite set of frames.

The program in the axiom HM$_8$ never loops.

We would like to attract the attention of the reader to the property HM$_4$. One may use it to deduce the important fact

Let T be any class, let (a$_1$, …, a$_k$) be a list of actual parametres. $\textbf{new }T(a_1, \dots , a_k) \neq \textbf{new }T(a_1, \dots , a_k)$

One can investigate the properties of the specification itself. We are able to state a couple of important metatheorems about the system of axioms HM.

(on consistency)
The system of axioms HM$_1$ – HM$_9$ has a model.

Proof. Using the ideas of the paper one can construct a programmable model of axioms HM$_1$ – HM$_9$.
This model will be called the standard model.

(representation theorem)
Every model of the axioms HM$_1$ – HM$_9$ is isomorphic to the standard one.

## Variations of axiom’s system

Are the simplifications we made important? One can easily observe two points:

• One can consider a slightly different operation reserve - with a parameter appetite defining the size required for an object. It leads to a consistent set of axioms.
• Another extension of our system HM is defined when one describes the internal structure of object. This extension is also consistent with our initial system.

Till now we needed not to introduce an operation of garbage collection. In our abstract version the set of Frames is isomorphic with the set of natural numbers.

One can ask how to express the property the set $Fr$ of frames is finite? The answer is easy:
HM$_{10}$) $\exists_{s_0 \in St} \forall_{f \in Fr} mb(f, s_0)$
Which reads: the set of frames is equal to some state, hence $Fr$ is a finite set.
Again, the set of the axioms HM$_1$ – HM$_{10}$ is consistent.

# Final remarks

In the paper the memory management system is treated as a whole. The problems of garbage collection and dangling references were not separated.

Operation kill can be safely implemented with low, fixed cost. The frequency of garbage collection is diminished due to following discipline

1. kill operation is called whenever an object should be deleted, the freed frame is added to the list of free memory frames,
2. the list of free memory frames is checked and used during an operation of new,
3. compactification (i.e. defragmentation) is done when needed,
4. instruction gc() is called when compactification did not help.

Let us remark that since Java was introduced in 1995 the memory size has grown thousand times.

# Acknowledgement

The second author was financed by research fellowship within the Project Information technologies: Research and its interdisciplinary applications, Agreement number UDA POKL.04.01.01-00-051/10-00.

1. The authors of use the word compactification.
2. One can add these ingredients of object’s size and its content later.
3. In Eiffel programming language, one finds invariants of classes. They are formulas of first-order language which limits their expressibility in an essential way.