Video in progress

Strong Middle 🧱 OOP and SOLID

How do you design an object that holds a resource (connection, file, lock)? Why is `finalize()` unusable?

You make the resource owner explicit, make the class AutoCloseable and close it with try-with-resources. finalize() has unknown timing (and may never run at all), is slow and is dangerous. It was deprecated in Java 9 and marked for removal in Java 18. Cleaner exists as a safety net.

📖 Answer

public final class ExportFile implements AutoCloseable {
    private final BufferedWriter out;
    private boolean closed;

    public ExportFile(Path path) throws IOException {
        this.out = Files.newBufferedWriter(path);
    }
    public void write(String line) throws IOException {
        if (closed) throw new IllegalStateException("yopilgan");
        out.write(line); out.newLine();
    }
    @Override public void close() throws IOException {
        if (!closed) { closed = true; out.close(); }   // idempotent
    }
}

try (var f = new ExportFile(path)) {
    f.write("id,summa");
}

Design rules:

  • Whoever opens it, closes it. If a method receives an InputStream as a parameter, it doesn't close it: that's the caller's resource. If it opened the stream itself, it closes it.
  • close() should be idempotent and give a clear error on calls after closing.
  • If you open a resource in the constructor and a later step fails, close what you opened and then throw the exception.

Problems with finalize(): you don't know when the GC will run, so file descriptors can run out; if the finalizer thread is slow, objects pile up in the queue and the heap fills up; and a "finalizer attack" can resurrect a half-built object. With JEP 421 it is on its way out.

java.lang.ref.Cleaner (Java 9) is only a safety net for "in case someone forgot close()", not the main mechanism.