With the try-with-resource introduced in Java 7, I was surprised to see that Lock not modified as AutoCloseable . It seemed pretty simple, so I added it as follows:
class Lock implements AutoCloseable { private final java.util.concurrent.locks.Lock _lock; Lock(java.util.concurrent.locks.Lock lock) { _lock = lock; _lock.lock(); } @Override public void close() { _lock.unlock(); } }
This works with the AutoCloseableReentrantReadWiteLock class, and usage is as follows:
try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) { // do something }
Since it seems such a simple and canonical use of automatic closing of RAII, I think that there should be a good reason why this should not be done. Somebody knows?
java raii try-with-resources
Miserable Variable May 15, '13 at 20:26 2013-05-15 20:26
source share