javasynchronizationlocks

Understanding locks usage in Java


I'm trying to understand the difference between synchronized and locks in Java and I found this other question that I still don't understand fully: What is the equivalent of synchronized( object ) in Reentrant lock in Java?

In particular I don't understand why the lock.lock() has been written outside the try block.

From what I understood locks are used inside method bodies and the lock.lock() is written as the first thing inside a try block to make sure that only one thread at a time can execute what's inside that try block, until the lock is unlocked with the lock.unlock() call, that is written in a finally block after the try block.

But if lock.lock() is invoked outside of a method body and outside of a block, what does that mean?


Solution

  • The try-finally construction is there to guarantee that the lock will be released.

    The reason why 'lock' is writen before 'try' is that, until locking is complete, there's nothing to unlock - so it's a bug to have a finally clause that unconditionally unlocks something that may not have been locked.