Why is synchronized block better than synchronized method?

后端 未结 10 988
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:32

    Define 'better'. A synchronized block is only better because it allows you to:

    1. Synchronize on a different object
    2. Limit the scope of synchronization

    Now your specific example is an example of the double-checked locking pattern which is suspect (in older Java versions it was broken, and it is easy to do it wrong).

    If your initialization is cheap, it might be better to initialize immediately with a final field, and not on the first request, it would also remove the need for synchronization.

提交回复
热议问题