0

What is the Re-entrant lock and concept in general? says

If a lock is non re-entrant you could grab the lock, then block when you go to grab it again, effectively deadlocking your own process.

public class ImplicitLock {

synchronized public void test1() {
    System.out.println("enter test1");
    test2();
    System.out.println("exit test1");

}

synchronized public void test2() {
    System.out.println("inside test2");

}

}

From main class , i executed

ImplicitLock lock1 = new ImplicitLock();
lock1.test1();

I got the below output though i was expecting deadlock when call goes for test2 as per SO implicit lock description but it didn't

enter test1
inside test2
exit test1
Community
  • 1
  • 1
emilly
  • 10,060
  • 33
  • 97
  • 172
  • see this SO [question](http://stackoverflow.com/questions/5787957/reentrant-synchronization-behavior-with-synchronized-statements). Synchronized blocks in java are reentrant. – Arkantos Mar 21 '15 at 14:06

2 Answers2

0

Java synchronized lock is reentrant. From Jakob Jenkov blog:

Lock Reentrance

Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same monitor object. Here is an example:

public class Reentrant{
    public synchronized outer(){
        inner();
    }
    public synchronized inner(){
        //do something
    }
}

Taken from: http://tutorials.jenkov.com/java-concurrency/locks.html

Shay Tsadok
  • 913
  • 1
  • 7
  • 26
  • Then what are Non re-entrant locks ? – emilly Mar 21 '15 at 14:04
  • AFAIK, Java JDK Locks are all re-entrant, but here is an example for how you can do it by your own: http://codereview.stackexchange.com/questions/17913/java-non-reentrant-lock-implementation – Shay Tsadok Mar 21 '15 at 14:09
0

You can say that implicit lock is reentrant. So basically if you try to lock it twice in the same thread you can because this thread already owns that lock.

See here http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

"A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements..."

jakub.petr
  • 2,951
  • 2
  • 23
  • 34