You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: java/ql/src/Violations of Best Practice/Undesirable Calls/DoNotCallFinalize.md
+35-4Lines changed: 35 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,14 +4,43 @@ Triggering garbage collection by directly calling `finalize()` may either have n
4
4
5
5
## Recommendation
6
6
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.
8
8
9
9
## Example
10
10
11
11
```java
12
-
publicclassTest {
13
-
voidf() throwsThrowable {
14
-
this.finalize(); // NON_COMPLIANT
12
+
classLocalCache {
13
+
privateCollection<File> cacheFiles =...;
14
+
// ...
15
+
}
16
+
17
+
void main() {
18
+
LocalCache cache =newLocalCache();
19
+
// ...
20
+
cache.finalize(); // NON_COMPLIANT
21
+
}
22
+
23
+
```
24
+
25
+
```java
26
+
importjava.lang.AutoCloseable;
27
+
importjava.lang.Override;
28
+
29
+
classLocalCacheimplementsAutoCloseable {
30
+
privateCollection<File> cacheFiles =...;
31
+
// ...
32
+
33
+
@Override
34
+
publicvoidclose() throwsException {
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 =newLocalCache()) {
43
+
// ...
15
44
}
16
45
}
17
46
@@ -25,4 +54,6 @@ This rule is focused on the use of existing `finalize()` invocations rather than
25
54
26
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).
27
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).
28
59
- Common Weakness Enumeration: [CWE-586](https://cwe.mitre.org/data/definitions/586).
0 commit comments