Why does try-with-resource require a local variable?

Miserable Variable picture Miserable Variable · May 16, 2013 · Viewed 12.6k times · Source

With reference to my question Any risk in a AutoCloseable wrapper for java.util.concurrent.locks.Lock?, I am wondering why the try-with-resource-statement require a named local variable at all.

My current usage is as follows:

try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) {
    // do something
}        

The variable l is unused inside the try block and only pollutes the namespace. From what I can remember the analogous C# using-statement does not require a local named variable.

Is there any reason the following could not have been supported, with an anonymous local variable that is closed at the end of try block?

try (_lock.writeLock()) {
    // do something
}        

Answer

Zero3 picture Zero3 · Jan 12, 2016

The link in the comment by @McDowell reveals the correct answer in a blog post comment by Joe Darcy who led the Java Technology Specification that introduced the try-with-resources statement:

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.