Java – advantages of locking API synchronization
•
Java
Every blog or explanation I see the advantages of locks API over synchronization
I want to know what the advantages of synchronous locking are, or any situation where I should prefer synchronization to locking
Solution
Do you mean synchronized statements and method keywords? The main advantage of implicit locking is that it requires less code and automatically unlocks when it leaves its scope It is the perfect solution for simple lock / wait operations
So the following code
public void myMethod() { synchronized(this) { // concurrent stuff } }
Exactly equivalent to
final private Lock lock = new reentrantlock(); public void myMethod() { lock.lock(); try { // concurrent stuff } finally { lock.unlock(); } }
and
synchronized public void myMethod() { // concurrent stuff }
You can also use different objects for synchronization (they are not affected, just as control points):
final static private Object sync = new Object(); public void method1() { synchronized(sync) { // concurrent code involving static members } } public void method2() { synchronized(this) { // concurrent code affecting this instance } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码