1.

What is synchronized method and synchronized block? Which one should be preferred?

Answer»

Synchronized Method: In this method, the thread acquires a lock on the object when they enter the synchronized method and releases the lock either normally or by THROWING an exception when they leave the method.  No other thread can use the whole method UNLESS and until the current thread finishes its execution and release the lock. It can be used when one WANTS to lock on the entire functionality of a particular method. 

Synchronized BLOCK: In this method, the thread acquires a lock on the object between parentheses after the synchronized keyword, and releases the lock when they leave the block. No other thread can acquire a lock on the locked object unless and until the synchronized block exists. It can be used when one wants to keep other parts of the programs accessible to other threads.
 
Synchronized blocks should be preferred more as it BOOSTS the performance of a particular program. It only locks a certain part of the program (critical section) rather than the entire method and therefore leads to less contention.



Discussion

No Comment Found