[Java] Closing of nested closables

Please follow this template to help us specify this new rule:

  • description of the Rule. It should answer questions “why is there an issue?”, “what could be its impact?” and “what could happen in case of a successful attack?” (for Vulnerabilities and Security Hotspots)

When using java classes that implement Closable or AutoClosable its important to close those resources after usage, this is normally done with the try-with-resources pattern. But sometimes you keep those resource as fields and only close them at the end. Currently there is no rule to detect this

  • snippet of Noncompliant Code
public class A {
  private B b = new B(); // implements AutoCloseable
  private C c = new C();
...
}
  • snippet of Compilant Code (fixing the above noncompliant code)
public class A implements AutoCloseable {
  private B b = new B(); // implements AutoCloseable
  private C c = new C();

  @Override
  public void close() {
    b.close();
  }
}

So there are two checks needed for compliance:

  1. if there is a field that implements closeable, the class containing it must also implement closeable
  2. this close method must call close on the field that implements closeable
  • exceptions to the Noncompliant Code, i.e. conditions in which the noncompliant code should not raise an issue so that we reduce the number of False Positives.

none

Hi there, this sounds like an interesting idea. I created this ticket to go deeper into specification of a new rule.

I think enforcing the parent class to implement AutoCloseable might be a stretch, but generally speaking I agree that it should be the parent’s class responsibility to make sure the AutoCloseable field is closed at some point.

Thanks about the insight!

1 Like