在Java 7中新的Try-with-Resources语法中,我是否需要担心资源的顺序?
try (InputStream in = loadInput(...); // <--- can these be in any order?
OutputStream out = createOutput(...) ){
copy(in, out);
}
catch (Exception e) {
// Problem reading and writing streams.
// Or problem opening one of them.
// If compound error closing streams occurs, it will be recorded on this exception
// as a "suppressedException".
}
Run Code Online (Sandbox Code Playgroud) Java-7的try-with-resources是否需要将closable直接分配给变量?简而言之,这段代码是......
try (final ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(data))) {
return ois.readObject();
}
Run Code Online (Sandbox Code Playgroud)
相当于这个块?...
try (final ByteArrayInputStream in = new ByteArrayInputStream(data);
final ObjectInputStream ois = new ObjectInputStream(in)) {
return ois.readObject();
}
Run Code Online (Sandbox Code Playgroud)
我对Java语言规范第14.20.3节的理解说它们不一样,必须分配资源.从常见的使用角度来看,这将是令人惊讶的,我找不到任何针对该模式的文档警告.
我已经阅读了这个主题,这篇关于尝试使用资源锁定的博客文章,正如我脑海中浮现的那样.但实际上,我更喜欢的是锁定尝试,我的意思是没有锁定实例化.它会让我们从冗长中解脱出来
lock.lock();
try {
//Do some synchronized actions throwing Exception
} finally {
//unlock even if Exception is thrown
lock.unlock();
}
Run Code Online (Sandbox Code Playgroud)
宁愿看起来像:
? implements Unlockable lock ;
...
try(lock) //implicitly calls lock.lock()
{
//Do some synchronized actions throwing Exception
} //implicitly calls finally{lock.unlock();}
Run Code Online (Sandbox Code Playgroud)
所以它不是TWR,而只是一些样板清洁.
您是否有任何技术理由建议描述为什么这不是一个合理的想法?
编辑:澄清我建议和简单synchronized(lock){}块之间的区别,检查这个片段:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
public static void main(String[] args) {
ReentrantLock locker =new ReentrantLock(); …Run Code Online (Sandbox Code Playgroud) 我正在创建多个流,我必须并行(或可能并行)访问.我知道如何在编译时修复资源量时尝试使用资源,但是如果资源量由参数确定怎么办?
我有这样的事情:
private static void foo(String path, String... files) throws IOException {
@SuppressWarnings("unchecked")
Stream<String>[] streams = new Stream[files.length];
try {
for (int i = 0; i < files.length; i++) {
final String file = files[i];
streams[i] = Files.lines(Paths.get(path, file))
.onClose(() -> System.out.println("Closed " + file));
}
// do something with streams
Stream.of(streams)
.parallel()
.flatMap(x -> x)
.distinct()
.sorted()
.limit(10)
.forEach(System.out::println);
}
finally {
for (Stream<String> s : streams) {
if (s != null) {
s.close();
}
}
}
}
Run Code Online (Sandbox Code Playgroud) try(InputStream in = url.openStream(); Scanner scanner = new Scanner(in).useDelimiter("\\A")) {
} catch(IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
线
新扫描仪
给出警告:
Resource leak: <unassigned Closeable> value' is never closed
Run Code Online (Sandbox Code Playgroud)
如果我删除,它消失了useDelimiter(String)。
useDelimiter(String)不返回新实例(返回this),那么为什么收到此警告?是虫子吗?
我正在使用Eclipse 4.4。我的问题与此无关,因为情况不同而发生警告
好了,在我的工作中,我们正在讨论试用资源和异常抑制.
快速回顾:来自java 7的try-with-resources消除了对那个讨厌的finally块关闭资源的需要.我个人认为它更优雅,但我有一个不相信的同事.他不喜欢一个例外被压制,并且一直在争论我们通过它来丢失信息.
起初我接受了他的话,因为我是一个初级开发者,他是高级,我是新人,等等.但我最近发现,嘿,所有信息都进入堆栈跟踪,包括被抑制的异常.所以没有信息丢失.
我正在寻找的这场辩论的最后一部分(因为我主张尝试使用资源)是自动关闭处理异常的方式.假设在尝试关闭资源时抛出异常,资源是否可能保持打开和泄漏?最终这可能不是什么大问题,因为无论如何日志都会提醒我们这个问题.
只是好奇.非常感谢.
自Java从1.7开始引入该语句以来,我就采用了以下规则来编写与光标相关的语句,如下所示:
try (Cursor cursor = context.getContentResolver().query(queryAccountUri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
entry.userId = cursor.getString(0);
entry.account = cursor.getString(1);
entry.phone = cursor.getString(2);
entry.nickName = cursor.getString(3);
entry.icon = cursor.getString(4);
}
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
但是,这些天,我们的测试人员不断通知我,该语句在运行猴子测试时仍然导致内存泄漏,或者如果对此方法进行循环测试,甚至会耗尽所有内存。cursor由于某些NOT CLOSING问题,所有日志文件都表明该对象是凶手。因此,我必须更改代码以cursor手动关闭对象,如下所示:
try {
if (cursor.moveToFirst()) {
entry.userId = cursor.getString(0);
entry.account = cursor.getString(1);
entry.phone = cursor.getString(2);
entry.nickName = cursor.getString(3);
entry.icon = cursor.getString(4);
}
} catch (NullPointerException e) {
e.printStackTrace();
} finally {
try …Run Code Online (Sandbox Code Playgroud) 是否必须将内部try-with-resources或其中一个try-with-resources中的所有内容自动关闭?
try (BasicDataSource ds = BasicDataSourceFactory.createDataSource(dsProperties)) {
// still necessary for Connection to close if inside
// try-with-resources?
try (Connection conn = ds.getConnection()) {
String sql = "SELECT * FROM users";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("email"));
System.out.println(rs.getString("password"));
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud) Clojure是否具有Java的try-with-resources构造的等价物?
如果没有,在Clojure代码中处理这个习惯用法的常用方法是什么?
用于安全打开和关闭资源的Java-7之前的习惯用语非常冗长,以至于它们实际上增加了对该语言的try-with-resources的支持.对我来说,在标准的Clojure库中找不到这个用例的宏似乎很奇怪.
基于Clojure的主流项目存储库的一个示例 - 显示如何在实践中处理此问题 - 将非常有用.
Files.walk是我应该关闭的流之一,但是,如何在下面的代码中关闭流?下面的代码是否有效,或者我是否需要重写它以便我可以访问流来关闭它?
List<Path> filesList = Files.walk(Paths.get(path)).filter(Files::isRegularFile ).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)