Reputation: 759
Suppose I have
class myClass {
synchronized methodA { };
synchronized methodB { };
}
Does it mean that there are 2 implicit locks? One for methodA and one for B? I was reading Cracking the Coding Interview by Gayle McDowell, and she says that locking happens at the level of method + object, as opposed to object. I was under the impression that myClass simply has one lock and every synchronized method uses that. Can anyone explain ?
Upvotes: 0
Views: 72
Reputation: 216
Both of this methods used same lock. Every object in java has his internal mutex.
synchronized void method() {}
and
synchronized(this) {}
used same lock.
But if you try synchronized on static method - it will use different locks:
static synchronized method() { // used Class lock ! not object lock
}
Upvotes: 0
Reputation: 2223
This
synchronized void methodA
{
//code
}
is equivalent to
void methodA
{
synchronized(this)
{
//code
}
}
So, synchronized
in front of a method will use the instance of the object itself as a lock.
Upvotes: 4