gpt4 book ai didi

Java 一次性模式

转载 作者:太空狗 更新时间:2023-10-29 23:04:26 25 4
gpt4 key购买 nike

C# 支持使用 dispose pattern 进行确定性垃圾回收的一次性模式.

java有这样的模式吗?

Java 7 有 autoclosable ,您可以将其与 try finally block 一起使用以调用 close 方法。

7 之前的版本呢?

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

最佳答案

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

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

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

您还应该考虑 Closeables在 Guava 中 - 它允许您不必担心引用是否为 null(就像 using 语句一样)并且可选地在关闭时抛出“logs and swallows”异常,以避免任何此类异常有效地“覆盖”从 try block 抛出的异常。

关于Java 一次性模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7773872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com