Reputation: 3197
In Java if a method is qualified by synchronized
keyword, it ensures that this method will be accessed by a single thread at any time, by manipulating objects monitor
such that when a thread enters a synchronized method it locks monitor
, so that all other threads know it is already locked by another thread.
My Question here is how does synchronized block achieve synchronization, What I mean is that there is no monitor
associated with this synchronized block so what indication it uses to determine if this block is already in execution? I am lost here.
Upvotes: 1
Views: 140
Reputation: 28099
Each object has an implicit lock associated with it. When entering a synchronized block, the process must acquire the object's lock before continuing. The lock is returned upon exiting the synchronized block.
public class SomeClass {
private Object mutex = new Object();
public static synchronized void method1() {
// static methods aquire the class level lock for SomeClass
}
public synchronized void method2() {
// aquire the lock associated with 'this' instance (of SomeClass)
}
public void method3() {
synchronized (mutex) {
// aquire the lock of the mutex object
}
}
}
Upvotes: 3