I have read that hashtables are thread-safe because it is synchronized. consider this code snippet
if(!hashtable.contains(key)){
hashtable.put(key,value);
}
The operations on hashtable may not be synchronized. for example, if Thread t1
access the hastable and check for key and at the same time Thread t2
checks for key, before t1 executes put. now two threads are inside the if block and overwriting of key-value happens.
so synchronized block is necessary.
synchronized {
if(!hashtable.contains(key)){
hashtable.put(key,value);
}
}
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 post on race condition
Hashtable
methods are synchronized, but that only provides method-level protection against race conditions. (So a Hashtable
—unlike a HashMap
—will not become internally corrupted if multiple threads are concurrently trying to modify the data.) It is only in this sense that Hashtable
is thread-safe.
Neither Hashtable
nor a ConcurrentHashMap
will provide higher-level synchronization, which is usually* what you need when you are performing multi-step operations. You need an external synchronized
block anyway, so you might as well use the lower-overhead HashMap
rather than a Hashtable
.
*As Jeff Storey points out, ConcurrentHashMap
has a putIfAbsent
method that does exactly what you are doing in your code. For other multi-step operations, ConcurrentHashMap
may or may not have a method that does what you need atomically.
You are correct that you need the synchronized
block. The Hashtable's
methods are synchronized
, but you still have the possibility of having a race when calling multiple methods outside of a synchronized
block. The built-in synchronization prevents problems when two threads call put
at the same time for example.
You might also want to look into ConcurrentHashMap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With