All of you know the synchronization context in Java that they are can be
And I need to ask; When i write
Dimension d = new Dimension();
synchronized(d){
// critical atomic operation
}
synchronization of a given object equal to synchronization on the instance practically.
so when I write synchronized(d) where d is an instance of object, then the thread will gain the lock for all synchronized instance block of code.
Can you please give me more details about synchronization context.
Your replies will be appreciated.
The synchronized
keyword provides serial access to the block of code (which could be an entire method) it introduces. Serialization of access is done by using an object as a mutex lock.
The three basic uses of synchronized
are:
A. On a static method:
static synchronized void someStaticMethod() {
// The Class object - ie "MyClass.class" - is the lock object for this block of code, which is the whole method
}
B. On an instance method:
synchronized void someInstanceMethod() {
// The instance - ie "this" - is lock object for this block of code, which is the whole method
}
C. On an arbitrary block of code:
private Object lock = new Object();
void someMethod() {
synchronized (lock) {
// The specified object is the lock object for this block of code
}
}
In all cases, only one thread at a time may enter the synchronized block.
In all cases, if the same lock object is used for multiple blocks, only one thread may enter any of the synchronised blocks. For example, if there are two - other simultaneous threads calling the methods will block until the first thread exits the method.
Applying the synchronized keyword to a non-static method is shorthand for:
public void method() {
synchronized(this) {
// method
}
}
If you apply synchronized
to a static method, then it locks the class object (MyClass.class) whilst the method is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With