Avoid Runtime.runFinalization()

ID

java.runtime_run_finalization

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

best-practice, reliability

Description

Reports calls to Runtime.getRuntime().runFinalization() and System.runFinalization().

Rationale

runFinalization() attempts to force the JVM to run pending finalizers. This is inherently unreliable: the JVM’s garbage collector uses sophisticated algorithms to decide when and how to collect objects, and calling runFinalization() interferes with those decisions, potentially degrading performance or causing premature resource release. Since Java 18, these methods are deprecated for removal.

// Bad
Runtime.getRuntime().runFinalization();
System.runFinalization();

Remediation

Use explicit resource management (try-with-resources or close() methods) instead of relying on finalization:

// Good - explicit resource management
try (var resource = openResource()) {
    process(resource);
}
// Resource is closed deterministically