>
>
>
V6114. The 'A' class containing Closeab…


V6114. The 'A' class containing Closeable members does not release the resources that the field is holding.

The analyzer has detected fields that implement the 'Closeable' (or 'AutoCloseable') interface in a class, but the 'close' method has not been called for them in any method of the analyzed class. Such code indicates that a resource may not be closed.

class A {
  private FileWriter resource;
  public A(String name) throws IOException {
    resource = new FileWriter(name); 
  }
  ....
}

In the above example, a developer initialized the 'resource' field but did not call the 'close' method within the 'A' class. The lack of a call to the close method results in the resource not being released even when the reference to the 'A' class object is lost. A program logic error may occur because of this. For example, if the resource is not released, we cannot access it from another part of the code.

We can fix it in several ways. One of them is to add the 'Closeable' or 'AutoClosable' interface with the 'close' method to the 'A' class where the resource is closed:

class A implements Closeable {
  private FileWriter resource;
  public A(String name) throws IOException {
    resource = new FileWriter(name); 
  }
  public void close() throws IOException {
    resource.close();
  }
}

Sometimes the program logic does not enable you to implement this interface in the class. An alternative solution would be to close the resource in one of the 'A' class methods:

class A {
  private FileWriter resource;
  public A(String name) throws IOException {
    resource = new FileWriter(name); 
  }
  public void method() throws IOException {
    .... 
    resource.close();
    .... 
  }
}

This diagnostic is classified as: