Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

后端 未结 23 2231
北荒
北荒 2020-11-22 04:29

Can any one tell me the advantage of synchronized method over synchronized block with an example?

23条回答
  •  执笔经年
    2020-11-22 04:53

    The only difference : synchronized blocks allows granular locking unlike synchronized method

    Basically synchronized block or methods have been used to write thread safe code by avoiding memory inconsistency errors.

    This question is very old and many things have been changed during last 7 years. New programming constructs have been introduced for thread safety.

    You can achieve thread safety by using advanced concurrency API instead of synchronied blocks. This documentation page provides good programming constructs to achieve thread safety.

    Lock Objects support locking idioms that simplify many concurrent applications.

    Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.

    Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

    Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.

    ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.

    Better replacement for synchronized is ReentrantLock, which uses Lock API

    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

    Example with locks:

    class X {
       private final ReentrantLock lock = new ReentrantLock();
       // ...
    
       public void m() {
         lock.lock();  // block until condition holds
         try {
           // ... method body
         } finally {
           lock.unlock()
         }
       }
     }
    

    Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.

    Refer to this related question too:

    Synchronization vs Lock

提交回复
热议问题