Regarding multiple locking attempts using java.concurrent.ReentrantLock

I noticed that the following code:

    final Lock s = new ReentrantLock();
    for(int i = 0 ; i < 1000 ; i++)
    {
        s.lock();
        System.out.println(i+" :" +s.tryLock()+" ");
    }

      

Prints:

0 :true 
1 :true 
2 :true 
3 :true 
...

      

It's odd - I would expect subsequent locks to fail since s is never unlocked.

Any errors here?

+3


source to share


4 answers


Javadoc is your friend . You should really read it.

From: ReentrantLock.lock ()



If the current thread already holds a lock, then the hold counter is incremented and the method returns immediately.

+10


source


I bet you lock it over and over again with the same thread. In this case, the thread already owns the lock, so the lock is successfully acquired (since it doesn't even need to be acquired).

A ReentrantLock belongs to the last successful blocking of the thread, but has not yet unlocked it. A thread call lock returns by successfully acquiring the lock when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock. This can be checked using the isHeldByCurrentThread () and getHoldCount () methods.



http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html

+6


source


ReentrantLock

is specially designed so that the same thread can acquire a lock more than once. Which means "reentrant". He had to exhibit this behavior from the very beginning.

+5


source


It always returns true because there is only one thread, and if thread1 detects s.lock () or s.tryLock () it will just increment the hold counter, and if another thread tries to execute that code, s.tryLock () method will return false because the lock will be acquired by thread1 .

0


source







All Articles