开发者

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 additio开发者_如何学JAVAn, 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.


You can use any reference type that does not have a weak identity to lock a block of code. It is a general practice to use the this pointer. But whether you should use a member variable depends on the behavior of your class.

For instance if you have four methods out of which two use var1 and the other two use var2. Now if you want to synchronize these methods only based on these variables then you could choose to use the variables to lock instead of this.


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


this is a pointer to the current object, but myMap is also an object, an instance of the class HashMap which implements the Serializable interface

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜