Destructors and finalizers
medium 45 minSome things must be given back: files, connections, locks.
Video lesson · Chapter 1 of 6
Make a prediction
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
1980
C with Classes has constructors and destructors from its first version (Stroustrup, A History of C++).
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.
2006
Python 2.5 gets the
withstatement (PEP 343, written in 2005).2011
Java 7 gets try-with-resources and
AutoCloseable.2014
Python 3.4 can collect reference cycles whose objects have
__del__(PEP 442).2017 and 2022
Java 9 deprecates
finalize()and addsCleaner. Java 18 deprecates finalization for removal (JEP 421).2023
TypeScript 5.2 supports
usingwithSymbol.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 bywith. - 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.
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.
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
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) # 3Constructor
- 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
newin 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
Destructor, close and finalizer side by side
| C++ destructor | close() with a block | Finalizer | |
|---|---|---|---|
| When | End of the owner's scope | End of the block | Unknown, perhaps never |
| Thread | Yours | Yours | Often another one |
| Order | Reverse of construction | Reverse of opening | None promised |
| Errors | Must not escape | Reach you | Ignored (Java), printed (Python) |
| If you forget | Cannot, for a local variable | Leak | That is its only use |
| Cost | A call | A call | Object lives for at least one more collection |
By language
The tool to reach for
| Language | Use | Not | Detail |
|---|---|---|---|
| C++ | RAII: std::unique_ptr, std::lock_guard, std::fstream, own destructors | delete by hand | Runs at the brace, also when an exception unwinds the stack to a handler |
| Java | AutoCloseable and try-with-resources | finalize() | Deprecated since 9, for removal since 18. Cleaner as a net |
| Python | with, contextlib | __del__ | Not guaranteed for objects that exist when the interpreter exits |
| C# | IDisposable and using | A finalizer of your own | SafeHandle for native handles |
| TypeScript, JavaScript | using with Symbol.dispose, await using with Symbol.asyncDispose, or try and finally | FinalizationRegistry for needed cleanup | TypeScript 5.2. Older: a helper function |
| Go | defer f.Close() | runtime.SetFinalizer | defer runs at the end of the function, not of the block |
| Rust | Drop | mem::forget | Ownership 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,
within 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
| Step | Runs | Why |
|---|---|---|
| 1 | The body of the class's own destructor | All members are still there |
| 2 | Its members, last declared first | Later members may refer to earlier ones |
| 3 | The base class's destructor | The base does not know the child |
| 4 | The memory is given back | delete or the end of the block |
Who owns, who only uses
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
| Problem | What happens |
|---|---|
| No promise | The program may end before it runs. Java's Cleaner documentation says the same for System.exit |
| Too late | It waits for memory pressure, while you are short of connections |
| Cost | The object and all it refers to live on until it has run |
| Wrong thread | It runs beside your code, so it needs locks, and locks in a finalizer can deadlock |
| Resurrection | It can make the object reachable again. Java then never finalizes it a second time |
| Lost errors | An exception in finalize() is ignored |
| Security | A 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
- Bjarne Stroustrup: A History of C++, 1979-1991
- Resource acquisition is initialization, history
- JEP 421: Deprecate Finalization for Removal
- Java: Cleaner
- Java: AutoCloseable
- Java tutorial: try-with-resources
- PEP 343: the with statement
- PEP 442: safe object finalization
- Python data model: __del__
- TypeScript 5.2: using declarations
- TC39 finished proposals
- ISO C++ FAQ: destructors
- .NET: implement a Dispose method
- HikariCP settings
- Netty: reference counted objects