Java 一次性模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7773872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Disposable pattern
提问by DarthVader
C# supports disposable pattern for deterministic garbage collection using the dispose pattern.
C# 支持使用dispose 模式进行确定性垃圾收集的一次性模式。
Is there such pattern for java?
java有这样的模式吗?
Java 7 has autoclosable
, which you can use with try finally blocks to invoke the close
method.
Java 7 具有autoclosable
,您可以将其与 try finally 块一起使用来调用该close
方法。
What about versions prior to 7?
7 之前的版本呢?
Is there a disposable pattern (deterministic garbage collection) for Java 5 or 6?
Java 5 或 6 是否有一次性模式(确定性垃圾收集)?
回答by Jon Skeet
The closest prior to Java 7 is just "manual" try/finally blocks:
Java 7 之前最接近的只是“手动” try/finally 块:
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 :)
using
当我第一次从 Java 背景开始使用 C# 1.0 时,该声明是我发现 C# 最好的事情之一。很高兴终于在 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.
您还应该考虑Closeables
在 Guava 中 - 它使您不必担心引用是否为空(就像using
语句一样)以及关闭时抛出的可选“记录和吞下”异常,以避免任何此类异常有效地“覆盖”从 try 块抛出的异常。
回答by Randolpho
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.
处置模式的全部目的是支持 C# 的独特using (temporaryObject)
模式。Java 在 7 之前没有类似的模式。
All Java objects that had resources supported the disposal pattern via manually closing the object that held resources.
所有拥有资源的 Java 对象都通过手动关闭拥有资源的对象来支持处置模式。
回答by Kevin Lafayette
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.
当然,资源必须是可关闭的(或可自动关闭的)。