引用我的问题 Any risk in a AutoCloseable wrapper for java.util.concurrent.locks.Lock? ,我想知道为什么 try-with-resource-statement 需要一个 named 局部变量。
我目前的使用情况如下:
try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) {
// do something
}
变量 l
在 try block 内未使用,只会污染命名空间。据我所知,类似的 C# using
语句不需要局部命名变量。
由于在 try block 结束时关闭了匿名局部变量,是否有任何原因无法支持以下内容?
try (_lock.writeLock()) {
// do something
}
最佳答案
@McDowell 评论中的链接揭示了 a blog post comment 中的正确答案由领导 the Java Technology Specification 的乔·达西 (Joe Darcy) 撰写引入了 try-with-resources 语句:
Back in JDK 7, we started with a try-with-resources construct like that allowed a general expression to be used for the resource, including a method call. However, the expert group found by the early draft review (http://jcp.org/aboutJava/communityprocess/edr/jsr334/index.html) that
"A possible future change [to the try-with-resources statemenbt] is dropping support for a resource to be specified as a general Expression. Nontrivial specification and implementation complexities arise from allowing a general Expression to be used as resource. A restricted expression that could be an identifier or a PrimaryNoNewArray may suffice. Even the more severe restriction of just allowing an identifier may provide nearly all the additional utility of allowing a full expression (over forcing the declaration of a new resource variable) at a much lower marginal implementation and specification impact."
By the end of JDK 7, what we wanted was a fresh variable declaration for the resource or an existing final / effectively final variable. We only had time to provide the former in 7; in 9, we are providing the latter too.
关于java - 为什么 try-with-resource 需要一个局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16588843/