RLK.FIELD
An RLK error indicates that a system resource was allocated and stored in a field, and there are no calls to methods that free this resource. The difference between RLK.FIELD and other RLK errors is that RLK.FIELD reports resources that are created and stored in a field (it is acceptable not to close the allocated resources immediately), and there are no methods where these resources are closed. Other RLK errors are reported for local variables (not fields). If a resource is not stored in a field, it should be closed after it is used. RLK.FIELD is reported only for private fields.
Checkers with the prefix RLK.* are resource leak checkers. All knowledge base checkers use the same parameter types: sources and sinks. Sources are methods that allocate resources, for example new FileInputStream(). Sink methods dispose resources, for example "close".
RLK.* errors may be reported for different resources: streams, SQL connections and SWT resources.
Vulnerability and risk
Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections.
Mitigation and prevention
Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors.
Example 1
class Logger {
private final PrintStream stream;
public Logger(String fileName)
throws FileNotFoundException {
if (fileName == null) stream = System.err;
else stream = new PrintStream(new FileOutputStream(
fileName));
}
public void warning(String str) {
System.out.print("Warning: " + str + ".\n");
}
}
RLK.FIELD is reported for field declaration on line 14: Possible leak of system resource 'java.io.PrintStream' stored in field 'stream'. Resource is not closed in any of the class methods.