Do Not Call finalize() Explicitly
ID |
java.call_finalize_explicitly |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:586, best-practice, reliability |
Description
Reports explicit calls to finalize() outside of a finalize() method’s super.finalize() chain.
Rationale
The finalize() method is designed to be invoked by the JVM garbage collector, not by application code. Calling it explicitly can release resources prematurely while other code still holds references, leading to use-after-free bugs, double-release issues, or undefined behavior. The only acceptable explicit call is super.finalize() inside a finalize() override to ensure proper cleanup chaining.
// Bad - explicit finalize call
public void cleanup() throws Throwable {
finalize();
}
Remediation
Use explicit resource management (try-with-resources, close(), or custom cleanup methods) instead of relying on finalization.
// Good - explicit resource management
public void cleanup() {
releaseResources();
}
// Acceptable - super.finalize() in finalize() override
@Override
protected void finalize() throws Throwable {
try {
cleanup();
} finally {
super.finalize();
}
}