Do singleton classes create problems in a multi-threaded app?

Viewed 5810

This might be premature optimization, or premature over-cautionization, but I'm avoiding using singletons on a few classes because I'm concerned that down the road I'll need to run my app as multi-threaded, and that the singletons will create conflicts and messiness. Do singletons have this issue in Ruby, or is there some kind of built in namespace so that when an a class refers to the singleton, only the singleton on the same thread is returned?

Edit: to clarify these are observable classes which when updated cause the other classes that are watching them to update. I'm not sure if this is thread safe or not, but I do know that right now I'm passing these observable classes around a ton and it's kind of annoying. And they do seem like natural singleton classes.

4 Answers

The Singleton Ruby mixin itself is thread safe. It means that you are guaranteed to get the same instance in all threads, and only that! It doesn't mean that methods which you implement for a singleton class by yourself will be thread safe.

If you look at the Singleton module implementation you'll see that #instance method uses Thread::Mutex#synchronize to guarantee thread safety of the method itself and also your class #initialize method. However, keeping your own singleton methods implementation thread safe is your responsibility!

Related