4

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 ?

jayunit100
  • 17,388
  • 22
  • 92
  • 167

4 Answers4

11

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.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
6

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

Corbin
  • 33,060
  • 6
  • 68
  • 78
5

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Really "reentrant" means thread-safe or more specifically it can be re-entered. http://en.wikipedia.org/wiki/Reentrancy_(computing) – Gray Mar 07 '12 at 22:26
  • http://en.wikipedia.org/wiki/Reentrant_mutex "In computer science, a reentrant mutex is a mutual exclusion, recursive lock mechanism. In a reentrant mutex, the same thread can acquire the lock multiple times." – Louis Wasserman Mar 07 '12 at 22:27
  • That's a definition of a "Reentrant_mutex". I was just commenting that the word "reentrant" has nothing to do with the thread obtaining the lock more than once. – Gray Mar 07 '12 at 22:30
0

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.

Bajrang Hudda
  • 3,028
  • 1
  • 36
  • 63