Safeguard
Application Security•

CWE-586 Explicit Call to finalize() in Java: Why Not

Calling finalize() yourself means it runs twice. Learn why CWE-586 causes unexpected state and how to fix it.

Safeguard Security Team
2 min read

CWE-586 is a Java weakness: code calls finalize() explicitly from outside the finalizer.

The Java Language Specification allows it. MITRE still calls it usually a bad idea. The garbage collector will call finalize() again when the object is collected, so your explicit call means cleanup runs more than once.

How it happens

MITRE's example:

// Vulnerable: manual cleanup via finalize
widget.finalize();

Cleanup code is rarely safe to run twice. The second run may free a handle that was already freed, close something another object now owns, or throw. If the object is still in use after the explicit call, it is also half destroyed.

What an attacker gains

MITRE lists integrity impact and unexpected state, along with quality degradation. Double release bugs can cause crashes or corrupted state.

How to find it

Automated static analysis can find some instances, per MITRE. Search for .finalize() calls outside a finalizer.

How to fix it

MITRE's mitigation: do not make explicit calls to finalize().

Give the class a proper close() method, make it idempotent, and call that.

// Fixed
public class Widget implements AutoCloseable {
    private boolean closed;
    @Override
    public void close() {
        if (!closed) {
            closed = true;
            releaseResources();
        }
    }
}

try (Widget w = new Widget()) {
    ...
}

Quick check

Why is calling finalize() a problem?

It runs once when you call it and again when the garbage collector collects the object.

The free in-browser scan at gold.safeguard.sh/scan lists the dependencies in your manifest. No login is needed, the file stays on your machine, and it handles up to 100 dependencies.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.