Lets say we have these 2 sample code :
public synchronized void getSomething(){ this.hello = "hello World"; }
and this one
public void getSomething(){ synchronized(this){ this.hello = "hello World"; } }
So some one can tell me what's the difference now?
Synchronized blocks provide granular control over a lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand, the synchronized method always locks either on the current object represented by this keyword or class level lock, if it's a static synchronized method.
synchronized (this) is syntax to implement block-level synchronization. It means that on this object only and only one thread can excute the enclosed block at one time.
Answer: Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
The two different methods are functionally equivalent. There may be a very small performance difference:
At the bytecode level, the synchronized method advertises its need for synchronization as a bit set in the method's access flag. The JVM looks for this bit flag and synchronizes appropriately.
The synchronized block implements its synchronization through a sequence of bytecode operations stored in the class file's definition of the method.
So the synchronized method might potentially execute slightly faster and take up less space in terms of bytecode.
Again, the two are, by specification, functionally identical.
I'm guessing that the performance difference is negligible and code style guidelines should win out. Some compilers might even optimize away the block into an access flag. And JIT may take the performance difference away.
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