I see in many tutorials for Reentrant lock, they create a new Reentrant lock and resource is injected, lock and unlock of reentrant lock is called in try/finally block. I don't understand the connection between this lock and resource which is used in the thread. Below is an example of tutorial on Reentrant lock
Resource code
public class Resource {
public void doSomething(){
//do some operation, DB read, write etc
}
public void doLogging(){
//logging, no need for thread safety
}
}
Resource being used in thread declaration code
public class ConcurrencyLockExample implements Runnable{
private Resource resource;
private Lock lock;
public ConcurrencyLockExample(Resource r){
this.resource = r;
this.lock = new ReentrantLock();
}
@Override
public void run() {
try {
if(lock.tryLock(10, TimeUnit.SECONDS)){
resource.doSomething();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
//release lock
lock.unlock();
}
resource.doLogging();
}
}
Can someone explain me how this prevents multiple threads from accessing the given resource at same time resulting in race condition??? Is this reentrant lock creating a Object level lock or Class level lock in the resource???