>
>
>
V6116. The class does not implement the…


V6116. The class does not implement the Closeable interface, but it contains the 'close' method that releases resources.

The analyzer has detected the 'close' method within which fields (resources) are released. However, the class does not implement the 'Closeable' or 'AutoCloseable' interface.

Such code can cause the following issues:

  • Another developer may forget to call the 'close' method without knowing about the implemented interface;
  • The IoC containers that manage the lifecycle of an object cannot call the 'close' method when the object is no longer needed. This is because containers analyze information about the implemented interfaces of an object.

In all of the above cases, the resources held by the object are not released. This may result in a program logic error. For example, if a resource is not released, it cannot be accessed from another part of the code.

Here is an example of the code that may cause errors:

class SomeClass {

  private FileWriter resource;
 
  public SomeClass(String name) {
    resource = new FileWriter(name); 
  }

  public void close() {
    resource.close();
  }
}

The fixed version of the 'SomeClass' class looks like this:

class SomeClass implements Closeable {

  private FileWriter resource;
 
  public SomeClass(String name) {
    resource = new FileWriter(name); 
  }

  public void close() {
    resource.close();
  }
}

There may be a case where the class implements the interface or is inherited from a class that already contains the 'close' method:

interface SomeInterface {
  public void close(); 
}

class SomeInterfaceImpl implements SomeInterface {
  private FileWriter resource;
  
  public SomeInterfaceImpl(String name) {
    resource = new FileWriter(name); 
  }
  
  public void close() {
    resource.close(); 
  }
}

In this case, three solutions exist. The first one is related to declaring the 'Closeable' (or 'AutoCloseable') interface in a class with the 'close' method:

class SomeInterfaceImpl implements SomeInterface, Closeable {
  private FileWriter resource;
  
  public SomeInterfaceImpl(String name) {
    resource = new FileWriter(name); 
  }
  
  public void close() {
    resource.close(); 
  }
}

The second solution is related to the interface inheritance. In the example above, you can declare 'SomeInterface' to extend the 'Closeable' (or 'AutoCloseable') interface.

interface SomeInterface extends Closeable {
  public void close(); 
}

If 'close' from 'SomeInterface' has implementations where no resource release occurs, or if inheriting 'Closeable' or 'AutoCloseable' is undesirable for some reason, then it is a good idea to rename the method, as this name is specific to these interfaces:

interface SomeInterface {
  public void shut(); 
}