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

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

    Most often I use this to synchronize access to a list or map but I don't want to block access to all methods of the object.

    In the following code one thread modifying the list will not block waiting for a thread that is modifying the map. If the methods were synchronized on the object then each method would have to wait even though the modifications they are making would not conflict.

    private List myList = new ArrayList();
    private Map();
    
    public void put( String s, Bar b ) {
      synchronized( myMap ) {
        myMap.put( s,b );
        // then some thing that may take a while like a database access or RPC or notifying listeners
      }
    }
    
    public void hasKey( String s, ) {
      synchronized( myMap ) {
        myMap.hasKey( s );
      }
    }
    
    public void add( Foo f ) {
      synchronized( myList ) {
        myList.add( f );
    // then some thing that may take a while like a database access or RPC or notifying listeners
      }
    }
    
    public Thing getMedianFoo() {
      Foo med = null;
      synchronized( myList ) {
        Collections.sort(myList);
        med = myList.get(myList.size()/2); 
      }
      return med;
    }
    

提交回复
热议问题