0

Hello I have question about ReentrantLocks in Concurrent package.

//First
Object ob = new Object();
synchronized(ob){

}

//Second
Lock lock = new ReentrantLock();
lock.lock();
try{

}
finally{
lock.unlock();
}

It says both Pieces of code are equivalent. What I don't get is in Fist piece synchronized block acquires the lock on obj object. But on what object does Reentrant lock acquire the lock on? Can I specify the object I want to lock on just like synchronized(obj)?

1 Answers1

0

Diving through the OpenJDK source (I started from http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/locks/ReentrantLock.java#ReentrantLock.lock%28%29), it ends up using an unsafe.compareAndSetInt if you've used the default ReentrantLock constructor. So although the code examples you list are functionally equivalent, they are not necessarily guaranteeing the same implementation.

Alex Taylor
  • 8,343
  • 4
  • 25
  • 40