我有代碼(簡化)這樣的:如何使用嵌套對象層次結構來確保資源被釋放?
class A {
B b = new B();
void close() {
b.close();
}
}
class B {
Closeable mustBeClosed = new Closeable() {
{
System.out.println("create");
}
@Override
public void close() {
System.out.println("close");
}
};
int n = 0/0;
void close() {
mustBeClosed.close();
}
}
//code
try (A a = new A()) {
//do something
}
如何保證mustBeClosed被釋放?
當對象層次結構複雜時,可能會發生這種情況。重寫最終確定B可能不是一個完美的解決方案。
針對這個問題的最佳實踐或原則?
修訂版的樣子:
class B {
Closeable mustBeClosed;
B() {
try {
mustBeClosed = ...
//other initialization which might raise exceptions
} catch (throwable t) {
close();
throw t;
}
}
void close() {
if (mustBeClosed != null) {
try {
mustBeClosed.close();
} catch (Throwable t) {
}
}
//all other resources that should be closed
}
}
然而,這需要太多的代碼是遠離優雅。更重要的是,所有權層次結構中的所有類似乎都應遵循相同的樣式,這會產生大量代碼。
有什麼建議嗎?