Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoCloseable "resource leak" warning for factory created instances?

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?

like image 643
antak Avatar asked Apr 24 '14 02:04

antak


1 Answers

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!)

like image 54
Stephen C Avatar answered Oct 09 '22 21:10

Stephen C