首页 > 解决方案 > 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.

标签: javaoop

解决方案


这里的工作示例

考虑 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 模式很重要。


推荐阅读