lock.lock() before try
java, java.util.concurrent, locking
Solution
Assuming that `lock` is a `ReentrantLock`, then it makes no real difference, since `lock()` does not throw any checked exceptions.
The Java documentation, however, leaves `lock()` outside the `try` block in the `ReentrantLock` example. The reason for this is that an unchecked exception in `lock()` should not lead to `unlock()` incorrectly being called. Whether correctness is a concern in the presence of an unchecked exception in `lock()` of all things, that is another discussion altogether.
It is a good coding practice in general to keep things like `try` blocks as fine-grained as possible.
Problem
Is there any difference between: ``` private Lock lock = new ReentrantLock(true); public void getIn (int direction) throws InterruptedException { lock.lock(); try { ... ``` and ``` ... public void getIn (int direction) throws InterruptedException { try { lock.lock(); ... ``` Compilation goes smoothly and also the program works (I mean the same output) Should I put lock.lock(); before or after try?... Thanks for any help