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
Lock is an interface. It defines a set of methods that all locks should have. ReentrantLock is a concrete class that implements the Lock interface. It implements all the methods defined in Lock , plus much more.
A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.
As the name says, ReentrantLock allows threads to enter into the lock on a resource more than once. When the thread first enters into the lock, a hold count is set to one. Before unlocking the thread can re-enter into lock again and every time hold count is incremented by one.
tryLock. boolean tryLock(long time, TimeUnit unit) throws InterruptedException. Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted. If the lock is available this method returns immediately with the value true .
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.
If case No 1, in finally
you can just say unlock()
. In case No2 you need to check if you are holding the lock before unlock()
, otherwise you can get IllegalMonitorStateException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With