user711189
user711189

Reputation: 4483

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?

Upvotes: 1

Views: 133

Answers (2)

Gray
Gray

Reputation: 116938

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());

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136152

  • 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

Upvotes: 1

Related Questions