Reputation: 17648
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 ?
Upvotes: 4
Views: 4472
Reputation: 3268
It is returning true always because there is only one thread and if a thread1 founds s.lock() or s.tryLock() it will just increment the hold count and if another thread will try to execute this code the method s.tryLock() will return false because the lock is acquired by thread1.
Upvotes: 0
Reputation: 198014
ReentrantLock
is specifically designed so that the same thread can obtain the lock more than once. That's what "reentrant" means. It was meant to exhibit this behavior from the beginning.
Upvotes: 5
Reputation: 76888
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.
Upvotes: 11
Reputation: 33437
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
Upvotes: 6