Reputation: 20779
These "resource leak" warnings I'm getting in Eclipse for AutoCloseable
s 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?
Upvotes: 13
Views: 1842
Reputation: 718826
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:
- If a method returns a resource to its caller, it is not responsible for closing; no problem is reported.
- If a resource is stored in a field, no single method is considered as responsible for closing; no problem is reported.
- 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.
- 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!)
Upvotes: 2