Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding multiple lock attempts, using java.concurrent.ReentrantLock

I've noticed that the following code block :

    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 
...

This is odd - I would expect the successive locks to fail , since s is never unlocked.

Any inisghts here ?

like image 806
jayunit100 Avatar asked Nov 30 '22 03:11

jayunit100


2 Answers

Javadoc is your friend. You really should be reading it.

From: ReentrantLock.lock()

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

like image 91
Brian Roach Avatar answered Dec 01 '22 15:12

Brian Roach


I bet you're locking it over and over again from the same thread. In which case, the thread already owns the lock, so the lock is successfully acquired (since it doesn't even have to be acquired).

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, 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 methods isHeldByCurrentThread(), and getHoldCount().

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

like image 35
Corbin Avatar answered Dec 01 '22 16:12

Corbin