tags:

views:

902

answers:

3

From the MSDN documentation:

"Synchronized supports multiple writing threads, provided that no threads are reading the Hashtable. The synchronized wrapper does not provide thread-safe access in the case of one or more readers and one or more writers."

Source: http://msdn.microsoft.com/en-us/library/system.collections.hashtable.synchronized.aspx

It sounds like I still have to use locks anyways, so my question is why would we use Hashtable.Synchronized at all?

+3  A: 

For the same reason there are different levels of DB transaction. You may care that writes are guaranteed, but not mind reading stale/possibly bad data.


EDIT I note that their specific example is an Enumerator. They can't handle this case in their wrapper, because if you break from the enumeration early, the wrapper class would have no way to know that it can release its lock.

Think instead of the case of a counter. Multiple threads can increase a value in the table, and you want to display the value of the count. It doesn't matter if you display 1,200,453 and the count is actually 1,200,454 - you just need it close. However, you don't want the data to be corrupt. This is a case where thread-safety is important for writes, but not reads.

Chris Marasti-Georg
when you say "you don't want the data to be corrupt", how would that look like if the data were corrupt? I consider displaying the wrong count as corrupt.
hmak
If Google says there are 1,200,453 pages because the 1,200,454th page was just added and the Hashtable entry that held the count was being updated right when the request was made, I wouldn't consider it a problem. The whole concept of sharded counters in GAE is based on this principle.
Chris Marasti-Georg
+1  A: 

For the case where you can guarantee that no reader will access the data structure when writing to it (or when you don't care reading wrong data). For example, where the structure is not continually being modified, but a one time calculation that you'll later have to access, although huge enough to warrant many threads writing to it.

Vinko Vrsalovic
so the final result of all the multi-thread writes to this synchronized data structure will be the same final result if I were to had a lock on the data structure?
hmak
yes (with the already noted exception)
Vinko Vrsalovic
A: 

you would need it when you are for-eaching over a hashtable on one thread (reads) and there exists other threads that may add/remove items to/from it (writes) ...

ehosca