Benefits of the Synchronization over Locks API

Every blog post or explanation I see the benefits of API Locks behind sync.

I want to know if there are any benefits of sync over locks or any scenario where I should prefer sync over locks.

+3


source to share


2 answers


Do you mean the synchronized statement and methods keyword? The main advantages of implicit locking are that it requires less code and is automatically unlocked when out of scope. For simple blocking / waiting operations, this is the ideal solution.

So the following code

public void myMethod() {
    synchronized(this) {
       // concurrent stuff
    }
}

      

excellent equivalent

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 in any way, being only checkpoints):

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
     }
}

      

+7


source


In addition to @ Shepard's answer, usage is synchronized

less error prone. Be aware of these errors that can lead to release locks:

final private Lock lock = new ReentrantLock();

public void myMethod() {
    lock.lock();
    // concurrent stuff
}

public void myMethod2() {
    lock.lock();
    // concurrent stuff that might throw an unchecked exception
    lock.unlock();
}

public void myMethod3() {
    lock.lock();
    try {
       // concurrent stuff
       lock.unlock();
    } catch ( ... ) {
       ...
    } finally {
       ...
    }
}

      

The first one may appear during testing, but the last two cannot.

You cannot make any of these mistakes with synchronized

.




However, Lock

useful despite these considerations:

  • Locks allow various locking strategies such as non-reentry locking and multi-reader / single author locking.

  • Locks allow you to hold locks on structure / structure boundaries. (This makes your code harder to reason about, but is necessary for some use cases, such as event-based, where locks need to be stored in multiple event handlers.)

  • The locking API allows you to test for locking, acquire a lock without a lock or with a timeout, and define objects Condition

    .

+6


source







All Articles