Skip to content

Commit 416643c

Browse files
Jami CogswellJami Cogswell
authored andcommitted
Java: update qhelp recommendation and example
1 parent caf21a8 commit 416643c

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

java/ql/src/Violations of Best Practice/Undesirable Calls/DoNotCallFinalize.md

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,43 @@ Triggering garbage collection by directly calling `finalize()` may either have n
44

55
## Recommendation
66

7-
Avoid calling `finalize()` in application code. Allow the JVM to determine a garbage collection schedule instead.
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.
88

99
## Example
1010

1111
```java
12-
public class Test {
13-
void f() throws Throwable {
14-
this.finalize(); // NON_COMPLIANT
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+
// ...
1544
}
1645
}
1746

@@ -25,4 +54,6 @@ This rule is focused on the use of existing `finalize()` invocations rather than
2554

2655
- 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).
2756
- 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).
2859
- Common Weakness Enumeration: [CWE-586](https://cwe.mitre.org/data/definitions/586).

0 commit comments

Comments
 (0)