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.
Only one thread will acquire the lock: this is the contract of ReentrantLock
.
Therefore your example 2 is perfectly thread safe.