Java / Java Multithreading
Difference between synchronized method and synchronized block in Java.
A synchronized method uses the method receiver as a lock, 'this' for non static methods and the enclosing class for static methods. Synchronized blocks uses the expression as a lock.
A synchronized method locks on the object instance the method is contained in while a synchronized block can lock on ANY object.
For synchronized methods, the lock will be held throughout the method scope, while in the synchronized block, the lock is held only during that block scope also known as critical section.
Synchronized block can throw NullPointerException if the expression provided as parameter evaluates to null, which is not the case with synchronized methods.
Synchronized block provides granular control over lock, as you can use any lock to provide mutual exclusion to critical section code. Synchronized method always lock either on current object or class level lock, if its static synchronized method.
Dogecoin! Earn free bitcoins up to $250 now by signing up.
Earn bitcoins upto $250 (free), invest in other Cryptocurrencies when you signup with blockfi. Use the referral link: Signup now and earn!
Using BlockFi, don't just buy crypto - start earning on it. Open an interest account with up to 8.6% APY, trade currencies, or borrow money without selling your assets.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
More Related questions...