Calling a synchronized method from of a synchronized method, both of the same object [duplicate]
Asked Answered
G

2

6

Why doesn't the code below lead to a deadlock? I mean after i call getNumber(.) the object of the class Test should be locked, so I shouldn't be able to access getNumber2(.).

class Test() {
    synchronized int getNumber(int i){
        return getNumber2(i);
    }

    synchronized int getNumber2(int i) {
        return i;
    }

    public static void main(String[] args) {
        System.out.println((new Test()).getNumber(100));
    }
}

Output:

100
Godspeed answered 4/3, 2013 at 14:34 Comment(2)
Similar post to this: #5799137Quarrel
Yes the question its the same, but the context its a quite different. On this question Its been asking about dead lock, the other one Its about thread safe.Republicanize
B
20

This is because the lock is re-entrant, meaning that it can be acquired multiple times by the same thread.

From the Java tutorial:

Reentrant Synchronization

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

The relevant part of the JLS is §17.1. Synchronization:

The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.

Belemnite answered 4/3, 2013 at 14:35 Comment(0)
B
4

It doesn't lead to a deadlock because when a thread enter a synchronized method, what it does is checking that it has a lock on this, then if it doesn't, it waits until it can have the lock and get it.

When the thread enters the second synchonized method in your case, it already has the lock on the this object, so it can enter the method without blocking.

Bawdry answered 4/3, 2013 at 14:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.