java - closing inaccesible resources
问题描述
How to manage the right way the state of a resource?
in java, sometimes we have resources that must to be opened and closed like
Scanner sc = new Scanner(File);
sc.close();
in complex scenarios is not that easy.
i'm facing this problem
foo(){
return new ClosableResourse();
}
bar(ClosableResourse foo){
return new NotAccesibleFoo(foo);
}
and 2 entities using this NotAccesibleFoo
. How i can properly close my ClosableResource
class?
bar() function is the only place where i can close that, but is needed in other entities and not accesible from them.
解决方案
这里的工作示例
考虑 Java 的try-with-resources特性,以及这个例子:
public class Example {
public static void main(String[] args) {
try (Bar b = new Bar()) {
b.bar();
}
}
}
在这里,如果Bar
实现AutoCloseable,则close()
自动调用。这可能与您的问题代码不完全匹配,但您可以close()
像这样链接:
class CloseableResource implements AutoCloseable {
@Override
public void close() {
System.out.println("TRACER CR close");
}
}
class Foo implements AutoCloseable {
CloseableResource resource = new CloseableResource();
@Override
public void close() {
System.out.println("TRACER Foo close");
resource.close();
}
}
class Bar implements AutoCloseable {
Foo foo = new Foo();
void bar() {}
@Override
public void close() {
System.out.println("TRACER Bar close");
foo.close();
}
}
在这种情况下,客户端代码(例如Example.java
这里)使用 try-with-resources 模式很重要。
推荐阅读
- javascript - 如何通过 Angular 4 中的 App 组件访问私有属性?
- php - htaccess 去除反斜杠
- swift - 多次添加 SCNNode 只显示一次
- wordpress - WP REST API 如何检查标头基本身份验证
- selenium - 我想 selenium 判断页面上的一些文字,返回 true,no false
- laravel-5 - 发送推送请求的错误请求
- css - bootstrap 4.1 - 仅获取网格系统
- javascript - React Native Jest 覆盖输出受 ES6 模块导出方式的影响
- php - $_FILE 在 $_post 中申请
- laravel - 在主机上使用自定义 /etc/host 为 Docker 提供网页服务