Why is synchronized block better than synchronized method?

后端 未结 10 960
Happy的楠姐
Happy的楠姐 2020-12-07 08:05

I have started learning synchronization in threading.

Synchronized method:

public class Counter {

   private static int count = 0;

   public stati         


        
10条回答
  •  借酒劲吻你
    2020-12-07 08:34

    Because lock is expensive, when you are using synchronized block you lock only if _instance == null, and after _instance finally initialized you'll never lock. But when you synchronize on method you lock unconditionally, even after the _instance is initialized. This is the idea behind double-checked locking optimization pattern http://en.wikipedia.org/wiki/Double-checked_locking.

提交回复
热议问题