AlgoViz

Destructors and finalizers

medium 45 min

Some things must be given back: files, connections, locks.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:37

Destructors and finalizers

1:04Reel

Theory

Read or listen first. About 2 min.

What it is

A destructor is code that runs when an object's life ends, at a moment you can point at in the source. In C++ it is ~File(), and it runs at the closing brace of the block that owns the object. It takes no parameters, and a class has exactly one.

A finalizer is code that a garbage collector may run some time after the object has become unreachable. Java's finalize(), C#'s ~File() (the same spelling, another thing), and in spirit JavaScript's FinalizationRegistry. You do not know when, and it may not run at all.

Python's __del__ is in between: CPython runs it when the last reference disappears, which is often at once. Other Pythons and reference cycles make it late.

Why it exists

Memory is plenty and a collector finds it. Other resources are few, and nobody looks for them: a database may allow 100 connections, a process may open some thousand files, and a lock has one holder.

The collector runs when memory is short, not when connections are short. A program can use up all its connections while memory is nearly empty, so no collection happens and no finalizer runs.

Giving back must happen on every way out of a block: at the end, at an early return, and when an error flies through. People forget one of them. Languages have therefore tied cleanup to a block.

A short history

  1. 1980

    C with Classes has constructors and destructors from its first version (Stroustrup, A History of C++).

  2. 1984 to 1989

    Bjarne Stroustrup and Andrew Koenig develop the technique that makes resources safe when exceptions fly. Stroustrup names it Resource Acquisition Is Initialization, RAII.

  3. 2006

    Python 2.5 gets the with statement (PEP 343, written in 2005).

  4. 2011

    Java 7 gets try-with-resources and AutoCloseable.

  5. 2014

    Python 3.4 can collect reference cycles whose objects have __del__ (PEP 442).

  6. 2017 and 2022

    Java 9 deprecates finalize() and adds Cleaner. Java 18 deprecates finalization for removal (JEP 421).

  7. 2023

    TypeScript 5.2 supports using with Symbol.dispose. The JavaScript proposal behind it is finished and is listed for ECMAScript 2027.

Words to know

Resource
Anything that must be given back: file, socket, connection, lock, GPU memory, listener.
Scope
The part of the program in which a name lives, usually a block.
Deterministic
You can say when it happens by reading the code.
RAII
Acquire in the constructor, release in the destructor. The object owns the resource.
Owner
The one that must release. There is exactly one at a time.
Idempotent
Doing it twice has the same effect as once.
Leak
A resource that is not used any more and not given back.
Context manager
Python: an object with __enter__ and __exit__, used by with.
Resurrection
A finalizer stores the object somewhere, and it is reachable again.
Dangling
A reference to something that is already gone.
Rule of zero, rule of five
C++: write none of destructor, copy and move, or think about all five.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Acquire. The constructor or a factory takes the resource

Understand it

Start here

Three lamps for a cave

A show cave lends helmets with lamps. There are three. Nobody minds an old sandwich paper in the cave, but a lamp left inside is missing at the entrance.

The lamps must come back
3 LAMPS

Frames 3 and 4 are finalizers. Frames 5 to 7 are destructors, with and using. Frame 8 is where a finalizer has its place.

First look

The bug and the block

Python
class Pool:    def __init__(self): self.free = 3    def take(self): self.free -= 1; return Lease(self)class Lease:    def __init__(self, pool): self.pool, self.open = pool, True    def close(self):        if self.open:            self.open = False            self.pool.free += 1    def __enter__(self): return self    def __exit__(self, *error): self.close()def work(text):    return int(text)pool = Pool()kept = []try:    lease = pool.take()    kept.append(lease)          # something still refers to it    work("x")                   # raises    lease.close()               # never reachedexcept ValueError:    print("by hand:", pool.free)    # 2pool = Pool()try:    with pool.take():        work("x")except ValueError:    print("with:", pool.free)       # 3
The same work twice. An error in the middle shows the difference.
Edit and run it in your browser

Constructor

  • Runs when the object is created
  • Acquires resources
  • Sets up the state
  • Can take parameters, can be overloaded
  • May throw: then there is no object

Destructor

  • Runs when the object's life ends
  • Releases resources
  • Leaves nothing behind
  • No parameters, only one
  • Should not throw: there is nobody to catch it well

What must be given back

  • Files

    Unflushed data may be lost, and on Windows an open file cannot be deleted.

  • Connections

    Database and network. Pools are small, servers limit clients.

  • Memory you manage

    new in C++, native buffers below Java or Python.

  • Locks

    A lock that is not released stops everybody else.

  • Graphics

    Textures and buffers on the GPU. The collector does not see that memory.

  • Handles and listeners

    Operating system handles, sockets, timers, event listeners.

How it works

The end of a life, two ways

Destructor: you can point at the moment

Finalizer: nobody knows when

Between Unreachable and Finalized there may be a millisecond or a month.

Destructor, close and finalizer side by side

C++ destructorclose() with a blockFinalizer
WhenEnd of the owner's scopeEnd of the blockUnknown, perhaps never
ThreadYoursYoursOften another one
OrderReverse of constructionReverse of openingNone promised
ErrorsMust not escapeReach youIgnored (Java), printed (Python)
If you forgetCannot, for a local variableLeakThat is its only use
CostA callA callObject lives for at least one more collection

By language

The tool to reach for

LanguageUseNotDetail
C++RAII: std::unique_ptr, std::lock_guard, std::fstream, own destructorsdelete by handRuns at the brace, also when an exception unwinds the stack to a handler
JavaAutoCloseable and try-with-resourcesfinalize()Deprecated since 9, for removal since 18. Cleaner as a net
Pythonwith, contextlib__del__Not guaranteed for objects that exist when the interpreter exits
C#IDisposable and usingA finalizer of your ownSafeHandle for native handles
TypeScript, JavaScriptusing with Symbol.dispose, await using with Symbol.asyncDispose, or try and finallyFinalizationRegistry for needed cleanupTypeScript 5.2. Older: a helper function
Godefer f.Close()runtime.SetFinalizerdefer runs at the end of the function, not of the block
RustDropmem::forgetOwnership decides the moment, the compiler checks it

Which tool?

Do

  • RAII in C++: acquire in the constructor, release in the destructor
  • try-with-resources in Java, with in Python
  • Rule of zero: let members clean up. Otherwise rule of five
  • Make close safe to call twice
  • Say in the documentation who must close

Avoid

  • finalize() in Java
  • Relying on __del__ in Python
  • Throwing from a destructor
  • Virtual calls in a destructor
  • Closing what you did not open

Order

Last in, first out

Objects are destroyed in the reverse order of their construction. A later one may use an earlier one, never the other way round. A statement uses the connection, so the statement goes first.

What runs when a C++ object dies

StepRunsWhy
1The body of the class's own destructorAll members are still there
2Its members, last declared firstLater members may refer to earlier ones
3The base class's destructorThe base does not know the child
4The memory is given backdelete or the end of the block
Exactly the mirror of construction.

Who owns, who only uses

Pool- free: List<int>+ take(): Lease~ giveBack(n)

1/4The pool

It lends numbers and takes them back. It is the only one that knows what is free.

usesowns (dies together)implements

Traps

Why finalizers disappoint

ProblemWhat happens
No promiseThe program may end before it runs. Java's Cleaner documentation says the same for System.exit
Too lateIt waits for memory pressure, while you are short of connections
CostThe object and all it refers to live on until it has run
Wrong threadIt runs beside your code, so it needs locks, and locks in a finalizer can deadlock
ResurrectionIt can make the object reachable again. Java then never finalizes it a second time
Lost errorsAn exception in finalize() is ignored
SecurityA subclass could get hold of an object whose constructor had failed

A class wraps a native image buffer of 8 MB. How is it released in Java?

Breaksfinalize()
How
Free the buffer there.
Limit
Java sees a tiny object and no pressure. 500 of them are 4 GB of native memory before a collection is due.
Choose when
Never in new code.
Worksclose() and good manners
How
AutoCloseable, used in try-with-resources.
Limit
One forgotten try and the buffer leaks without a sign.
Choose when
Small programs, few users of the class.
Strongclose() plus a Cleaner that reports
How
The state sits in a static class that does not refer to the owner. The Cleaner frees it and logs where it was made.
Limit
More code, and the log comes late.
Choose when
Libraries, anything native or pooled.

Summary

The whole topic in one minute.

Tie each resource to a block: RAII in C++, with in Python, try-with-resources in Java, using in C# and TypeScript, defer in Go. It is released on every way out, in reverse order.

Make close idempotent, with one owner, and do not let it hide the error that was already flying. Report its own error where somebody can read it.

Finalizers are a net under the trapeze: they report what fell and perhaps save it. They are not part of the act.

  • Deterministic cleanup for resources, the collector for memory.
  • One owner, one block, release in reverse order on every way out.
  • close() may be called twice and does no harm.
  • A cleanup error must not hide the first error.
  • C++: rule of zero if you can, rule of five if you own something raw, virtual destructor for a base that is deleted through a pointer.
  • Finalizers only report and rescue.

Sources