Java一次性模式 [英] Java Disposable pattern

查看:103
本文介绍了Java一次性模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#支持使用处理模式

Java是否有这样的模式?



Java 7有 autoclosable ,您可以使用它尝试finally块来调用 close 方法。



7之前的版本如何?



对于Java 5或6,是否存在一次性模式(确定性垃圾回收)?

解决方案

最接近Java 7之前的是手动try / finally块:

  FileInputStream input = new FileInputStream(... ); 
尝试{
//使用输入
} finally {
input.close();

使用语句的是当我第一次从Java背景开始使用C#1.0时,我发现最好的关于C#的东西之一。最好在Java 7中看到它:)



您还应该考虑 Closeables 在番石榴 - 它可以让你不用担心关于引用是否为空(就像使用语句一样),还可以选择记录并吞下关闭时抛出的异常,以避免任何这样的异常有效地覆盖从try块引发的异常。


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?

解决方案

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.

这篇关于Java一次性模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆