Skip to content
Advertisement

Are Locks AutoCloseable?

Are Locks auto-closeable? That is, instead of:

JavaScript

…can I say:

JavaScript

…in Java 7?

Advertisement

Answer

No, neither the Lock interface (nor the ReentrantLock class) implement the AutoCloseable 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:

JavaScript

Now you can write code like this:

JavaScript

I think you’re better off sticking with the old syntax, though. It’s safer to have your locking logic fully visible.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement