Hashtable.Clear thread-safety?

style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">Q: Is it safe for a single writer to
call Hashtable.Clear() with multiple concurrent readers? o ns = "urn:schemas-microsoft-com:office:office" />

style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 

style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">A: (from the developer that owns
Hashtable) It depends on what you want. Clear() will not cause a hashtable to be
inconsistent state, so hashtable will be not corrupted. The document says
Hashtable is thread-safe for a single writer and concurrent readers, but
unfortunately the current implementation doesn’t completely hold that up. style="mso-spacerun: yes">  The race condition happens when we copy
a hashtable bucket in reader and writer is reusing the same bucket. style="mso-spacerun: yes"> By reusing I mean the writer frees a
bucket and add a new item to the same bucket. Since a bucket contains hashcode,
key and value. We might copy the key from the old item and the value from the
new item. So in theory you can still hit this problem if you clear all the items
in a hashtable and then insert a new one, although you might never hit it in

style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">Remove and Clear are the only
functions which will free a bucket. Value is written before keys in Add, but key
is set to null before value is set to null in Clear and Remove. So it is
possible your reader has copied a key in a bucket and then Writer kicks in and
changes the value to null. A more serious problem is that you can get a value
which belongs to another key. That will cause grief. Changing the order will not
solve the problem.

style="FONT-SIZE: 10pt; FONT-FAMILY: Arial; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA">You
can use System.Threading.ReaderWriterLock to do the synchronization or use
Hashtable.Synchronized to get a synchronized wrapper

Comments (1)

Skip to main content