Hello,
I have a false positive S2095 with SonarLint V5.2.0.35150 running in IntelliJ 2021.2.1 Ultimate.
I use a class that implements the AutoCloseable
interface. The class is instantiated and initialized in a builder method. The returned instance is used in a try-with-resources.
The code looks like this:
private class SomeAutoCloseable implements AutoCloseable {
// Whatever methods
// This is the close method of the AutoCloseable interface
@Override
public void close() {
// Clean up the instance
}
}
private void aWorkerMethod() {
// The AutoCloseable object is used here in a try-with-resources
try (SomeAutoCloseable sac = aBuilderMethod()) {
// Use the SomeAutoCloseable instance
}
}
private SomeAutoCloseable aBuilderMethod() {
final SomeAutoCloseable result = new SomeAutoCloseable();
// Fill the SomeAutoCloseable and return it as the result of the builder method
return result;
}
SonarLint shows a bug S2095 in the line
final SomeAutoCloseable result = new SomeAutoCloseable();
in the method aBuilderMethod
and complains that the instance should be closed. However, the instance is returned as the result of the method and this returned instance is used in a try-with-resources. It does not make sense to close it in the builder method.