Memory and the garbage collector: Java and C++

A C++ programmer knows when an object dies: at the closing brace of its scope, in reverse order, by the destructor the class wrote. A Java programmer does not know, and mostly does not care, because the collector frees memory when it wants. The two habits meet at the resource that is not memory: a file, a socket, a lock. There the Java object has to be closed, and the collector will not do it for you.

The task

A handle that prints when it is opened, used and closed, and a program that uses one inside a block and one outside it. The prints make the moment of closing visible, which is the whole subject: in C++ the destructor closes the first handle at the brace, and in Java the block closes it only because the program asked.

The Java version

Handle implements AutoCloseable, so a try-with-resources may own it. The resource is closed at the end of the block, before the next statement, and the compiler inserts the call: a class that implements the interface gets the guarantee, and a class that does not cannot be put in the header.

public class Lifetime { static class Handle implements AutoCloseable { private final String name; Handle(String name) { this.name = name; System.out.println("open " + name); } void use() { System.out.println("using " + name); } @Override public void close() { System.out.println("close " + name); } } public static void main(String[] args) { try (Handle file = new Handle("file")) { file.use(); } System.out.println("after the block"); Handle leaked = new Handle("leaked"); leaked.use(); leaked.close(); Holder holder = new Holder(); holder.value = "text"; holder = null; System.out.println("the object is unreachable now"); } static class Holder { String value; } }

javac -Xlint:all -d out Lifetime.java
java -cp out Lifetime

open file
using file
close file
after the block
open leaked
using leaked
close leaked
the object is unreachable now

The first three lines are the block: open, use, close, and only then after the block. The second handle is closed by hand, which works and relies on the author remembering. The Holder at the end is never closed, because it holds nothing but a reference: it becomes unreachable when the variable is nulled, and the collector frees it whenever it likes.

The C++ version

The same class in C++ has a destructor, and the same program has no second close: the braces do it. This block is not compiled on this page, because the image has no g++; it is the code a C++ compiler would see, and the text says what it does.

#include <iostream> #include <string> class Handle { public: explicit Handle(std::string name) : name_(std::move(name)) { std::cout << "open " << name_ << '\n'; } ~Handle() { std::cout << "close " << name_ << '\n'; } void use() const { std::cout << "using " << name_ << '\n'; } private: std::string name_; }; int main() { { Handle file("file"); file.use(); } std::cout << "after the block\n"; Handle leaked("leaked"); leaked.use(); std::cout << "the object is still alive\n"; }

The program would print the same first four lines, and then it would differ: the second handle is closed at the closing brace of main, after the last line, because its scope is the function. There is no way to write the C++ version so that a live object is not destroyed at the end of its scope, and no way to write the Java version so that a reachable object is.

What differs and why

The C++ rule is scope: a destructor runs at a known point, in a known order, and a class that owns a resource can be written so that the resource is never leaked. The Java rule is reachability: an object is freed when nothing can reach it, and the moment is the collector's. That is why Java has no destructor and why finalize was deprecated in Java 9 and removed as a mechanism in later versions: a finalizer runs at an unknown time, on a collector thread, and may not run at all.

The bridge is AutoCloseable and the try-with-resources, which the course covers in lesson 098. It gives the deterministic close of RAII for anything that declares itself closeable. What it does not give is the C++ guarantee that every resource-owning type is closed: a Java class may hold a file and implement nothing, and the compiler will not object.

Memory itself is the other half. C++ gives memory back with delete or a smart pointer, and a program that forgets leaks until it dies. Java gives it back by itself, and a program that keeps a reference leaks until the reference goes away. The two failures look the same in a profiler and have opposite fixes: one is a missing delete, the other is a field that should have been cleared.

The habit that breaks

The C++ programmer's habit is to assume that the end of a scope closes everything. In Java it closes nothing. A method that opens a stream, returns early on a condition and leaves the close to the end of the method leaks a file descriptor on the early path, and no collector will save it: the descriptor is not memory, and the object that holds it may stay reachable for the life of the program.

The second habit is to write a finalizer or a Cleaner as a safety net and to trust it. A cleaner runs when the object is unreachable, which may be never, and a program that relies on it has a resource whose lifetime is the collector's decision. The rule is the same as in C++: the code that opens a resource closes it, in a try-with-resources, and the collector is left to the memory.

The next page

The next page is generics against templates: the same function for two types, and the different moment at which each compiler complains. The C++ course lesson for this ground is RAII, and the Java lesson is memory and the garbage collector.

The Java program was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The C++ program is shown and was not compiled here: the image has no g++.

Article author: Arthur Isaev