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

后端 未结 23 1991
北荒
北荒 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 05:05

    I know this is an old question, but with my quick read of the responses here, I didn't really see anyone mention that at times a synchronized method may be the wrong lock.
    From Java Concurrency In Practice (pg. 72):

    public class ListHelper {
      public List list = Collections.syncrhonizedList(new ArrayList<>());
    ...
    
    public syncrhonized boolean putIfAbsent(E x) {
     boolean absent = !list.contains(x);
    if(absent) {
     list.add(x);
    }
    return absent;
    }
    

    The above code has the appearance of being thread-safe. However, in reality it is not. In this case the lock is obtained on the instance of the class. However, it is possible for the list to be modified by another thread not using that method. The correct approach would be to use

    public boolean putIfAbsent(E x) {
     synchronized(list) {
      boolean absent = !list.contains(x);
      if(absent) {
        list.add(x);
      }
      return absent;
    }
    }
    

    The above code would block all threads trying to modify list from modifying the list until the synchronized block has completed.

提交回复
热议问题