When to use synchronized

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);
              }
          }
+3
source share
4 answers

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).


It may be lockused elsewhere in the code and is there for some reason. (?)

+4
source

There is a race condition between containsKey () and remove (). Lock prevents race condition.

However, its pretty pointless because you can just call remove ().

+3
source

- , synchronized(content), Hashtable.

, (Object) , , Java.

:

private Hashtable content = new Hashtable();

public void deleteContent(Object key){
    content.remove(key);
}

public Object getContent(Object key){
    return content.get(key);
}
+1

If this hash table is accessed simultaneously using different methods, the search or removal of elements must be synchronized to prevent simultaneous modification!

0
source

All Articles