|
| 1 | +## Overview |
| 2 | + |
| 3 | +Triggering garbage collection by directly calling `finalize()` may either have no effect or trigger unnecessary garbage collection, leading to erratic behavior, performance issues, or deadlock. |
| 4 | + |
| 5 | +## Recommendation |
| 6 | + |
| 7 | +Avoid calling `finalize()` in application code. Allow the JVM to determine a garbage collection schedule instead. If you need to explicitly release resources, provide a specific method to do so, such as by implementing the `AutoCloseable` interface and overriding its `close` method. You can then use a `try-with-resources` block to ensure that the resource is closed. |
| 8 | + |
| 9 | +## Example |
| 10 | + |
| 11 | +```java |
| 12 | +class LocalCache { |
| 13 | + private Collection<File> cacheFiles = ...; |
| 14 | + // ... |
| 15 | +} |
| 16 | + |
| 17 | +void main() { |
| 18 | + LocalCache cache = new LocalCache(); |
| 19 | + // ... |
| 20 | + cache.finalize(); // NON_COMPLIANT |
| 21 | +} |
| 22 | + |
| 23 | +``` |
| 24 | + |
| 25 | +```java |
| 26 | +import java.lang.AutoCloseable; |
| 27 | +import java.lang.Override; |
| 28 | + |
| 29 | +class LocalCache implements AutoCloseable { |
| 30 | + private Collection<File> cacheFiles = ...; |
| 31 | + // ... |
| 32 | + |
| 33 | + @Override |
| 34 | + public void close() throws Exception { |
| 35 | + // release resources here if required |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +void main() { |
| 40 | + // COMPLIANT: uses try-with-resources to ensure that |
| 41 | + // a resource implementing AutoCloseable is closed. |
| 42 | + try (LocalCache cache = new LocalCache()) { |
| 43 | + // ... |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +``` |
| 48 | + |
| 49 | +# Implementation Notes |
| 50 | + |
| 51 | +This rule ignores `super.finalize()` calls that occur within `finalize()` overrides since calling the superclass finalizer is required when overriding `finalize()`. Also, although overriding `finalize()` is not recommended, this rule only alerts on direct calls to `finalize()` and does not alert on method declarations overriding `finalize()`. |
| 52 | + |
| 53 | +## References |
| 54 | + |
| 55 | +- SEI CERT Oracle Coding Standard for Java: [MET12-J. Do not use finalizers](https://wiki.sei.cmu.edu/confluence/display/java/MET12-J.+Do+not+use+finalizers). |
| 56 | +- Java API Specification: [Object.finalize()](https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#finalize()). |
| 57 | +- Java API Specification: [Interface AutoCloseable](https://docs.oracle.com/javase/10/docs/api/java/lang/AutoCloseable.html). |
| 58 | +- Java SE Documentation: [The try-with-resources Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). |
| 59 | +- Common Weakness Enumeration: [CWE-586](https://cwe.mitre.org/data/definitions/586). |
0 commit comments