AutoCloseable "resource leak" warning for factory created instances?
Asked Answered
H

1

13

These "resource leak" warnings I'm getting in Eclipse for AutoCloseables seem to be a life-saver.

However, how do I get them to work for factory created instances?

For example (a works, but b doesn't):

public static void main(String[] args) {
    // a) This emits a warning
    new AutoCloseable() {
        @Override
        public void close() throws Exception {}
    };

    // b) But this doesn't!
    newResource();
}

public static AutoCloseable newResource() {
    return new AutoCloseable() {
        @Override
        public void close() throws Exception {}
    };
}

Is there an annotation I can stick on newResource() or something I can do to let the compiler (or is it Eclipse?) know of the ownership change?

Heighttopaper answered 24/4, 2014 at 2:31 Comment(2)
Intellij can generally warn if some return values are disregarded. This could help as you would than have to assign the value locally.Bergren
Try this: https://mcmap.net/q/438582/-using-annotation-to-ensure-that-value-returned-by-method-is-not-discardedBergren
W
2

The Neon Eclipse documentation on "resource leak" detection explains what is going on; see "avoiding resource leaks". It states:

Ownership / responsibility

The above diagnostics basically assume that a method that creates an instance of a resource type is also responsible for closing this resource. However, some resources will be shared among several methods. Here the analysis makes the following assumptions:

  1. If a method returns a resource to its caller, it is not responsible for closing; no problem is reported.
  2. If a resource is stored in a field, no single method is considered as responsible for closing; no problem is reported.
  3. If a method obtains a resource via a method call rather than by a new expression, it may or may not be responsible; any problems are only flagged as potential resource leaks.
  4. If a resource is passed as an argument in a method call or constructor call, the current method may or may not be responsible; any problems are only flagged as potential resource leaks.

Point #1 explains why there is no "resource leak" warning for the return statement in the newResource method.

Point #3 explains why there is no "resource leak" warning for the newResource() call. At best, it would be a "potential resource leak" warning. Either you have those warnings disabled, or the previous warning is inhibiting it.


Q: Is there an annotation to tell Eclipse about transfer of resource ownership?

A: The Neon Eclipse documentation doesn't mention any such annotation. (And it does go into detail about the annotations for null checking!)

Wheaten answered 30/3, 2018 at 8:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.