Java Disposable pattern

孤者浪人 提交于 2019-12-01 13:58:40

问题


C# supports disposable pattern for deterministic garbage collection using the dispose pattern.

Is there such pattern for java?

Java 7 has autoclosable, which you can use with try finally blocks to invoke the close method.

What about versions prior to 7?

Is there a disposable pattern (deterministic garbage collection) for Java 5 or 6?


回答1:


The closest prior to Java 7 is just "manual" try/finally blocks:

FileInputStream input = new FileInputStream(...);
try {
  // Use input
} finally {
  input.close();
}

The using statement was one of the things I found nicest about C# when I first started using C# 1.0 from a Java background. It's good to see it finally in Java 7 :)

You should also consider Closeables in Guava - it allows you to not worry about whether or not a reference is null (just like a using statement does) and optionally "logs and swallows" exceptions thrown when closing, to avoid any such exception from effectively "overwriting" an exception thrown from the try block.




回答2:


The entire purpose of the disposal pattern is to support C#'s unique using (temporaryObject) pattern. Java has had nothing like that pattern before 7.

All Java objects that had resources supported the disposal pattern via manually closing the object that held resources.




回答3:


What you are looking for is try with resources.

try ( FileInputStream input = new FileInputStream(...);
      BufferedReader br = new BufferedReader(...) ) {
  // Use input
} 

The resource has to be Closeable (or AutoCloseable), of course.



来源:https://stackoverflow.com/questions/7773872/java-disposable-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!