Click to See Complete Forum and Search --> : Static / Singleton Classes + Multiple Threads


Grofit
December 18th, 2009, 02:21 AM
Hey,

I was having a conversation with a guy at work the other day and we were talking about singletons and he mentioned that only one thread can access a singleton at any given time, so the entire class/instance is entirely locked out to any other threads...

Im currently working on a distributed node system, so i have lots of apps that can sit on various servers and just wait to be sent information then process it and send it back. Now a few of these use singletons to manage cached collections of related data but as the requests come asynchronously and apparently static and singleton classes cannot allow multiple threads to use them at the same time (even with manual lock handling in place) i just wanted to see if anyone could shed any more light on this. As ideally i want multiple threads and be able to read from these singletons as there is more reads than there are writes...

The other reason i ask is because im writing quite a few Extension methods, and im wondering if they suffer from the same problem... im hoping its hogwash and you can use singletons and just put your own locking mechanisms in place, but like always im sure im wrong :(

Mutant_Fruit
December 18th, 2009, 04:39 AM
he mentioned that only one thread can access a singleton at any given time, so the entire class/instance is entirely locked out to any other threads.

He's wrong ;) The only way to enforce this is to explicitly code that support by using lock statements (or similar). By default there is no thread safety supplied.

Grofit
December 18th, 2009, 05:26 AM
Woohoo!

Thats a worry off my mind, thanks for the confirmation...

dannystommen
December 18th, 2009, 05:33 AM
By default there is no thread safety supplied.

That's not completly true. This MSDN article (http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) says about the List<t> and Thread Safety the next:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.


And I can remember seeing this line in other articles as well

boudino
December 18th, 2009, 05:59 AM
Yes, but is is enforced by programmer who coded it this way, there is nothing like default thread safety for static members. Only one which could be considered exception is that if the class is loaded for first time, the class (static) constructor is thread safe.

Mutant_Fruit
December 18th, 2009, 06:01 AM
That's not completly true. This MSDN article (http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) says about the List<t> and Thread Safety the next:


And I can remember seeing this line in other articles as well

Exactly as boudino said. Support for this was added by the MS programmers. The .NET runtime offers you no protection by default for accessing/modifying shared state with multiple threads.