Singleton and Hashtable Help?

L

localhost

I have a Hashtable that is a property of a Singleton.
Clients do a GetInstance() on the Singleton and then call a read or
write method to
perform work on the Hashtable.

I am worried that this is not thread-safe. Or because the Hashtable
is a property of the
Singleton, maybe it is.

Is it?

Thanks.
 
J

John Saunders

localhost said:
I have a Hashtable that is a property of a Singleton.
Clients do a GetInstance() on the Singleton and then call a read or
write method to
perform work on the Hashtable.

I am worried that this is not thread-safe. Or because the Hashtable
is a property of the
Singleton, maybe it is.

Is it?

Singletons are not automatically thread-safe. They have the exact same
thread safety problems as any shared instance.

Only they're worse than most situations, because you _know_ there's only one
instance, so you _know_ that multiple threads _will_ be accessing it
simultaneously, so you _really_ can't get away with ignoring synchronization
issues.

You should absolutely assume that everything that can go wrong will go
wrong, unless you do something about it. To my mind, it's likely that Murphy
was writing multithreaded code (on a multiple-CPU system) when he thought of
his Law.

John Saunders
 
M

Mr. Mountain

These all seem like good comments. I'm sure that singletons might be worse
for the reasons John mentions. However, it seems they might also be better
because one might be able to design access, via the single entry point of
GetInstance(), so that synchronization problems are more easily dealt with
in the code. I guess this depends on the specifics of the code at hand, but
I can imagine many situations where the singleton pattern might be a big
help in organizing multi-threaded code.

It seems like Jon Skeet has some info on this very topic on his web site. I
haven't read it or seen it, but I do remember a post where Jon mentions
something on this topic. It may be worthwhile to take a look over at
http://www.yoda.arachsys.com/csharp/threads/index.shtml
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top