gpt4 book ai didi

java - 工厂创建实例的 AutoCloseable "resource leak"警告?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:02:03 25 4
gpt4 key购买 nike

我在 Eclipse 中针对 AutoCloseable 收到的这些“资源泄漏”警告似乎是救命稻草。

但是,如何让它们为工厂创建的实例工作?

例如(a 有效,但 b 无效):

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 {}
};
}

是否有我可以在 newResource() 上添加注释或者我可以做些什么让编译器(或者是 Eclipse?)知道所有权更改?

最佳答案

关于“资源泄漏”检测的 Neon Eclipse 文档解释了正在发生的事情;见"avoiding resource leaks" .它指出:

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.

第 1 点解释了为什么 newResource 方法中的 return 语句没有“资源泄漏”警告。

第 3 点解释了为什么 newResource() 调用没有“资源泄漏”警告。充其量,这将是一个“潜在资源泄漏”警告。您禁用了这些警告,或者之前的警告正在禁止它。


问:是否有注释告诉 Eclipse 资源所有权的转移?

答:Neon Eclipse 文档没有提到任何此类注释。 (它确实详细介绍了空检查的注释!)

关于java - 工厂创建实例的 AutoCloseable "resource leak"警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23258753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com