Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lock.lock() before try [duplicate]

Tags:

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

like image 316
9628001 Avatar asked Jun 03 '12 06:06

9628001


People also ask

What is the difference between lock and ReentrantLock?

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.

What is lock in multithreading?

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.

What is the use of ReentrantLock in java?

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.

What is tryLock in java?

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 .


2 Answers

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.

like image 144
thkala Avatar answered Sep 22 '22 14:09

thkala


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

like image 37
Op De Cirkel Avatar answered Sep 21 '22 14:09

Op De Cirkel