简体   繁体   中英

Java concurrency try to lock

public class TestConcurrent{

 public static void main(String args[]){
    Lock lock = new ReentrantLock();
    boolean b1 = lock.tryLock();
    System.out.println(b1); //prints true       
    boolean b2 = lock.tryLock();
    System.out.println(b2); //prints true again
 }
}

The first try to lock manages to lock the object successfully. About the second try, I would suppose that the second try to lock will return false since the object hasn't been unlocked yet. However it returns true again!!

Any explanation to this?

To quote from the ReentrantLock.tryLock() Javadocs :

If the current thread already holds this lock then the hold count is incremented by one and the method returns true.

If another thread tried to do the lock then it will return false . But since it is the same thread that is locking again, it will return true and increment the hold count by one. This means that you will have to unlock() it twice before other threads can get the lock() .

You can see this by looking at the hold-count:

Lock lock = new ReentrantLock();
assertEquals(0, lock.getHoldCount());
boolean b1 = lock.tryLock();
System.out.println(b1); //prints true       
assertEquals(1, lock.getHoldCount());
boolean b2 = lock.tryLock();
System.out.println(b2); //prints true again
assertEquals(2, lock.getHoldCount());
  • List item

This is only because you are aquiring the lock twice but from the same thread. This is the same as here

synchronized void x() {
    y();
}

synchronized void y() {
}

the thread will not block on y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM