Are Locks AutoCloseable? 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?
Building on Stephen's answer and user2357112's idea, I have written the following class.
The MyLock class itself is not closeable itself, to force users of the class to call get().
Here is a typical use:
No, neither the
Lock
interface (nor theReentrantLock
class) implement theAutoCloseable
interface, 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.
Taking user2357112's shrewd advice into account:
Use:
Could be interesting to make
CloseableLock
implementjava.util.concurrent.locks.Lock
.I was looking into doing this myself and did something like this:
and then this as usage for the class:
There's no perfect solution, unless you ignore the allocation costs (most application programmers can, but the lock library writers can not). Then you can use a wrapper
in this construct
See also my question on CR.