Are Locks auto-closeable? That is, instead of:
Lock someLock = new ReentrantLock();
someLock.lock();
try
{
// ...
}
finally
{
someLock.unlock();
}
…can I say:
try (Lock someLock = new ReentrantLock())
{
someLock.lock();
// ...
}
…in Java 7?
No, neither the
Lockinterface (nor theReentrantLockclass) implement theAutoCloseableinterface, which is required for use with the new try-with-resource syntax.If you wanted to get this to work, you could write a simple wrapper:
Now you can write code like this:
I think you’re better off sticking with the old syntax, though. It’s safer to have your locking logic fully visible.