Java Disposable pattern

前端 未结 3 1721

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

Is there such pattern for java?

Java 7 has autoclosable, whic

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 11:29

    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.

提交回复
热议问题