Search code examples
variableslockingblockprivatesynchronized

using a private variable for the lock of synchronized block


hi there i am working on threads and implement some simple examples with them. In addition, i know how to lock and use a synchronized statement but i saw an example like this;

private List<Foo> myList = new ArrayList<Foo>();
private Map<String,Bar) myMap = new HashMap<String,Bar>();

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
  }
}

so how and why can be a variable used as a lock of a synchronized block_?. i always using "this" word for accessing to the statement.


Solution

  • In Java, each object instance has a lock associated with it. You need a object's reference in order to do a synchronized block statement. It's not necessary to use the same object for a synchronized block. You would be perfectly fine with this:

    private Map<String,Bar) myMap = new HashMap<String,Bar>();
    private Object lockObj = new Object();
    
    public void put( String s, Bar b ) {
      synchronized( lockObj ) {
        myMap.put( s,b );
        // then some thing that may take a while like a database access or RPC or notifying listeners
      }
    }
    

    But the trick now, is to make sure you use the same object whenever you access myMap object. So it's a good practice to use the same object that you operation on, to act as a lock.. This is used when you want to do a small synchronized block and don't bother creating a new object for it.. this will work fine for that. I hope that helped you understand java's synchronization approach.

    Regards, Tiberiu