I have a question about stateless singletons. I also have a question about singletons with state.
Stateless singleton services are a good way to help with scalability. The programmer who architected the project which I maintain basically said there'll be no concurrency issues because "it is just code" (the Singleton class, that is). Meaning the class has no class level variables. It is just methods.
This is where my knowledge of C# gets a little hazy. Is there any possible issue where 2 users, via separate web requests, hit the stateless singleton at the same time? Could they end up in the same method at the same time? Is that even possible? If so, does that mean they'd be using the same local variables in that method? Sounds like a big mess, so I'm assuming it just can't happen. I'm assuming that somehow method calls are never polluted by other users.
I've asked many colleagues about this and no-one knows the answer. So it is a tricky issue.
My question about singletons generally is whether there is any problem with 2 or more concurrent users reading a public property of a Singleton. I'm only interested in reads. Is there a possibility of some kind of concurrency exception where a property is not inside a lock block? Or are concurrent, simultaneous reads safe? I don't really want to use the lock keyword, as that is a performance hit that I don't need.
Thanks
Singleton is an anti-pattern. A stateless singleton is even worse. If something does not hold state, there is not even the faintest reason to make it a singleton.
A stateless singleton is a pure static function from someone who enjoyed adding a pattern without thinking about what the pattern would achieve. Because in this case, he would have noticed that it achieves nothing.
If you see a stateless singleton, you can safely remove every bit of code that makes it a singleton. Add a
staticto the class definition. Done. Way better than before.I think you are pretty confused about multi threading, singleton or not. I suggest you read a good book or tutorial on this because it's way out of scope for a simple answer here. If you have shared resources (simple example, a variable that is not a local) then you need to take special care in multi-threaded environments.
If you are reading more often than writing, using a
ReaderWriterLockinstead of a simplelockmight be beneficial. See here.