Rule Definition
Object.finalize() method are supposed to be invoked at most one time by the garbage collector on Objects which are no longer referenced. This method can be invoked by another thread in parallel. Explicit invocation of a finalizer ignores the current state of the object and does not change the state of the object from unfinalized or finalizable to finalized.
Remediation
If an explicit call to finalize method is required, there is two possible remediation:
- if finalize method is used to release non-memory resources like file handles, sockets, database connections etc: you must not use this method to release these resources but create a specific method or release these resource in a finally block. Finalize() method is used only to release memory resources.
- if it is used for memory resources, the Garbage collector will handle the invocation, so just remove the explicit call.
Violation Code Sample
public class MyClass {
...
protected void finalize() throws Throwable {
// some code here
......
super.finalize();
}
}
public class InvokeFinalize {
private MyClass mine = new MyClass();
...
public meth () {
...
mine.finalize(); // VIOLATION
}
}
Fixed Code Sample
public class InvokeFinalize {
private MyClass mine = new MyClass();
...
public meth () {
...
/ FIXED
}
}
Reference
http://www.owasp.org/index.php/Poor_Style:_Explicit_call_to_finalize()
Related Technologies
JEE
Technical Criterion
Efficiency - Memory, Network and Disk Space Management
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.