Extending try-with-resources to open as well as close

Stephen Colebourne scolebourne at joda.org
Sat Mar 2 04:23:37 UTC 2019

Following Stuart's recent core-libs-dev email [1], I wanted to discuss
extensions to user-defined control abstraction. Control abstraction
remains a very important alternative to lambdas, particularly for
return early from a method, checked exceptions and simpler
debugging/stack traces. Java's approach of calling out to a helper
interface (Iterable/AutoCloseable) is reasonable enough, but
definitely only covers a limited subset of use cases. What about
java.util.concurrent.locks.Lock for example?

Currently, it is possible to write a wrapper to work with
try-with-resources [2]:

 try (Object ignored = new LockWrapper(lock)) { ... }

Sadly, the Java 9 changes to try-with-resources don't help, as that
only allows a variable, not an expression, so we can't do this via a
void-returning default method on Lock:

 try (lock.open()) { ... }

One possible amber change would be to allow arbitrary expressions in
try-with-resources but I understand there are concerns with that (and
its been looked at twice already).

With _ representing an ignored variable, we might soon be able to get
to this, which is still non-optimal but doesn't require a language

 try (var _ = lock.open()) { ... }

If a new interface was added, `AutoOpenCloseable`, it would be
possible to make `java.util.concurrent.locks.Lock` implement it. The
try-with-resources JLS spec would also be expanded to say that if the
variable passed in implements `AutoOpenCloseable` then `open()` would
be called. the code necessary would then be:

 try (lock) { ... }

This feels like a relatively simple change (looks can be deceiving of
course). But are there are other use cases for wrapping open/close
behaviour around code without needing to use an additional object for
the opened state?


[1] https://mail.openjdk.java.net/pipermail/core-libs-dev/2019-March/058780.html
[2] https://stackoverflow.com/questions/6965731/are-locks-autocloseable

More information about the amber-dev mailing list