With try-with-resource introduced in Java 7, I was surprised to see that that the Lock has not been retrofitted to be an AutoCloseable. It seemed fairly simple, so I have added it myself 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 an AutoCloseableReentrantReadWiteLock class and usage is as follows:
try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) {
// do something
}
Since this seems so straightforward and canonical use of auto-closing RAII I am thinking there must be a good reason this should not be done. Anybody know?