Java 一次性模式

发布于 2024-12-09 23:16:54 字数 417 浏览 4 评论 0 原文

C# 支持使用 处置模式进行确定性垃圾收集的一次性模式

java有这样的模式吗?

Java 7 具有 自动关闭,您可以将其与 try finally 块一起使用来调用 close 方法。

7 之前的版本怎么样?

Java 5 或 6 是否有一次性模式(确定性垃圾收集)?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱的故事 2024-12-16 23:16:55

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

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

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

您还应该考虑 Closeables - 它使您不必担心引用是否为 null(就像 using 语句一样)做)和可选“记录并吞下”关闭时引发的异常,以避免任何此类异常有效地“覆盖”从 try 块引发的异常。

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.

驱逐舰岛风号 2024-12-16 23:16:55

处置模式的全部目的是支持 C# 独特的 using (temporaryObject) 模式。 Java 在 7 之前没有类似的模式。

所有拥有资源的 Java 对象都支持通过手动关闭持有资源的对象来处理模式。

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.

嗳卜坏 2024-12-16 23:16:55

您正在寻找的是尝试资源。

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

当然,资源必须是可关闭的(或自动关闭的)。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文