I am wondering what is the reason for the synchronization of the code below. I don’t think a deadlock could happen?
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 is Hashtablealready synchronized, and the method removedoes nothing if the key is not in the table. Thus, all blocks synchronizedcan be deleted (also check containsKey).
Hashtable
remove
synchronized
containsKey
It may be lockused elsewhere in the code and is there for some reason. (?)
lock
There is a race condition between containsKey () and remove (). Lock prevents race condition.
However, its pretty pointless because you can just call remove ().
- , synchronized(content), Hashtable.
synchronized(content)
, (Object) , , Java.
:
private Hashtable content = new Hashtable(); public void deleteContent(Object key){ content.remove(key); } public Object getContent(Object key){ return content.get(key); }
If this hash table is accessed simultaneously using different methods, the search or removal of elements must be synchronized to prevent simultaneous modification!