I hear a lot about "Singletons are always bad" around the place. I don't hate on them to that degree but I try not to use them if I have a better alternative.
In this case I have a system that handles a lot of requests, each of which comes in on its own thread. Every request that comes in needs to be allocated its own unique sequential Id.
Currently I have a Singleton class whose role is to initiate this Id at start-up then maintain it while the system runs. The Singleton is created/retrieved and the Id value incremented in a thread safe way, as one would expect. It is actually handed out to the threads on creation by Dependency Injection, but the core of the class is a classic Singleton built around a static representation of the current Id value.
Given that we are only likely to do more work that requires a multi-threaded approach, I would be interested to know whether there is a way I could implement this type of functionality in a way that allows data to be maintained synchronously across threads that are otherwise unaware of each other, without using the much feared Singleton pattern?
getInstance()
then injecting the result? It's also not clear why the current Id would need to be static, if you only have one instance of the class. Could you post some code? – Karl Bielefeldt Mar 20 '13 at 15:37