title: hashtable and synchronization in Java
body: <p>I have read that hashtables are thread-safe because it is synchronized. consider this code snippet</p>
  
  <pre><code>if(!hashtable.contains(key)){
  hashtable.put(key,value);
  }
  </code></pre>
  
  <p>The operations on hashtable may not be synchronized. for example, if <code>Thread t1</code> access the hastable and check for key and at the same time <code>Thread t2</code> checks for key, before t1 executes put. now two threads are inside the if block and overwriting of key-value happens.</p>
  
  <p>so synchronized block is necessary.</p>
  
  <pre><code>synchronized {
  if(!hashtable.contains(key)){
      hashtable.put(key,value);
      }
  }
  </code></pre>
  
  <p>Is this understanding correct? or is hastables safe on the operations that is performed upon hastables. I got this doubt while I was reading this <a href="http://javarevisited.blogspot.sg/2012/02/what-is-race-condition-in.html" rel="noreferrer">post on race condition</a></p>