nascent
nascent

Reputation: 117

Is lock released when non synchronised method is called

If i have a methodA which is synchronized

public synchronized void methodA() {
    // ... Some code
    methodB();
    // ... Some more code
}

I have a methodB which is not synchronized and called from methodA

private void methodB() {
    // ...
}

Thread will acquire a lock and enter into methodA. My doubt is when methodB is called from methodA is the lock released and acquired again when controll goes back to methodA.

Upvotes: 0

Views: 118

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533442

No. The only method which does this is Object.wait();

e.g.

public synchronized void methodA() {
    // ... Some code
    // releases the lock, waits 1000 ms or until notify()ed, & regains the lock.
    wait(1000); 
    // .. some code.
    methodB(); // doesn't do anything to the lock
    // ... Some more code
}

Note: as it DOESN'T release the lock you have the possibility of a deadlock with multiple locks.

class MyClass {
    public synchronized void methodA(MyClass mc) {
         mc.methodB();
    }

    public synchronized void methodB() {
         // something
    }
}

static MyClass MC1 = new MyClass(), MC2 = new MyClass();

If you have one thread which calls

MC1.methodA(MC2);

and another which calls

MC2.methodA(MC1);

you can get a deadlock. This is because first method locks one object and the second call locks the other. As the thread do this in different orders, it is possible for each thread to hold the lock the other one needs.

Upvotes: 7

Related Questions