When to use synchronized
I'm wondering what is the reason behind synchronizing the below code. I开发者_如何学编程 don't think deadlock could occur ?
private final Object lock = new Object();
private Hashtable content = new Hashtable();
public void deleteContent(Object key){
synchronized(lock){
if(content.containsKey(key)){
content.remove(key);
}
}
}
public Object getContent(Object key){
synchronized(lock){
return (Object) content.get(key);
}
}
I have no idea.
The implementation of Hashtable
is already synchronized and the remove
method does nothing if the key isn't in the table. So all synchronized
blocks can be removed (also the containsKey
check).
Maybe the lock
is used elsewhere in the code and is there for a reason. (?)
There is a race condition between containsKey() and remove(). A lock avoid the race condition.
However its rather pointless becasue you can just call remove() alone.
You are correct -- if they were to synchronize it, they should do synchronized(content)
, which is what all Hashtable
methods are synchronized on.
Also that cast to (Object) shows whoever wrote this has only read the cover of a Java book.
This is just as good:
private Hashtable content = new Hashtable();
public void deleteContent(Object key){
content.remove(key);
}
public Object getContent(Object key){
return content.get(key);
}
If that hashtable is being accessed by concurrently by different methods, retrieval or deleting of elements would have to be synchronized to prevent concurrent modification!
精彩评论