0

I searched a lot but was confused with the process of 'ReentrantLock' and normal 'synchronized' .

For example(1):

Object obj = new Object();

synchronized(obj){
//lock is guaranteed to be acquired 
}

example(2)

Lock lock = new ReentrantLock();
lock.lock(); //problem here
try{
//dostuff
}
finally{
lock.unlock();
}

My question is:

In example 1: it is guaranteed to acquire a lock on the object using the synchronized keyword.

But

In example 2: is it guaranteed that the lock will be acquired using the lock.lock() method?? or will the thread proceed to the next line for the execution?? without acquiring the lock.

I doubt it because, using threads had resulted in unexpected outcomes for me many times.

ak500
  • 33
  • 4
  • Isn't this the whole rationale for using Lock objects? To have an unambiguous lock object, one without any other purpose and that functions well. – Hovercraft Full Of Eels Nov 14 '15 at 04:09
  • this may help: http://stackoverflow.com/questions/11821801/why-use-a-reentrantlock-if-one-can-use-synchronizedthis – adhg Nov 14 '15 at 20:05

1 Answers1

5

Only one thread will acquire the lock: this is the contract of ReentrantLock.

Therefore your example 2 is perfectly thread safe.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118