12得票2回答
我的AutoCloseable.close()实现可以检测到潜在的异常吗?

当使用实现 AutoCloseable 接口的对象来配合 Java 7 的 try-with-resources 语句时,我想知道在 try 块中是否发生了异常。例如:class C implements AutoCloseable { @Override public voi...

11得票2回答
关闭CloseableHttpResponse/CloseableHttpClient的正确方法

我正在使用CloseableHttpResponse(来自apache-httpclient-4.5.3),但我不确定我是否使用正确,我看到一个没有投票的答案,建议在finally中使用EntityUtils.consume CloseableHttpResponse response1 ...

11得票2回答
为什么Java7特别引入了AutoCloseable接口?

AutoCloseable在jdk1.7中引入,而Cloesable已经存在于jdk1.5。 根据https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html的说法: try-with...

11得票4回答
Java8中的“Autocloseable”数组或集合

Autocloseable 应该总是与 try-with-resources 一起使用。至少Intellij检查建议如此。 因此,如果我有一个生产实现了 Autocloseable 的 Foo 的代码,那么我应该这样做:try (final Foo foo = getFoo()) { ...

10得票3回答
什么是Java中代码执行时间计时的简洁方法?

计时代码执行可以很方便地了解事情需要多长时间。然而,我发现通常这样做的方式很草率,因为它应该具有相同的缩进,这使得更难以阅读实际计时的内容。 long start = System.nanoTime(); // The code you want to time long end = S...

10得票2回答
尝试使用资源关闭顺序

我正在查看Java中try-with-resources的示例,我理解以下内容: try (Connection conn = DriverManager.getConnection(url, user, pwd); Statement stmt = conn.createStat...

9得票1回答
当在try-with-resources块之外流式传输JOOQ结果时,我是否会面临JDBC连接泄漏的风险?

我有一个JOQ查询,我希望避免同时实例化所有记录。(但是,我可以共同实例化从它们创建的所有bean对象。) 我有以下简单方法来加载数据: public List<CustomerInfo> getCustomers() { return dslContext ...

9得票1回答
处理let绑定或函数体中发生的异常该如何处理?

当在let语句的绑定或主体中可能出现异常时,如何使用相同的finally块处理这些异常?例如: (let [connections (create-connections)] (dostuff) (close connections)) 如果(create-connection...

9得票1回答
使用lambda表达式作为没有实现AutoCloseable的类的替代方案是否安全、正确和等价?

背景:我使用Java类InitialDirContext来访问LDAP目录。不幸的是,它没有实现接口AutoCloseable,因此不能在try-with-resources块中使用。 以下是我编写的原始代码(受此答案启发): final Properties props = new Pr...

8得票3回答
自动关闭作为参数传递的资源

如果我想自动关闭作为参数传递的资源,是否有比这更优雅的解决方案? void doSomething(OutputStream out) { try (OutputStream closeable = out) { // do something with the OutputS...