开发者

Singletons in multi threaded environment

when using singletons, if the class has instance fields should you be careful 开发者_Python百科when several threads might be using the singleton? (And the fields are mutable and their values can be changed)

I havn't tried but in theory it seems like the answer is yes and you would need synchronization (or skip the singleton)


When you access an object (or the same mutable data) from multiple threads (or processes) you will need some kind of synchronization. There is no difference whether it is a singleton or any other "non-singleton" object.

One additional question, in case of singletons is the creation of the singleton though, if this is created the first time it is used, then the first time might be concurrently for different threads, so you will need to synchronize singleton-creation as well.


When using a singleton, the instance is shared by all the threads in the application, so yes, extra care should be taken to ensure that no concurrency problem arise.

However, this proble, is not specific to singletons, and should be considered whenever an object instance is shared between multiple threads.


Yes you need to synchronize access to all fields of the singleton, otherwise you will wreak havoc with state of your object.

On the other hand, if you can avoid the singleton in a multi-threaded environment, you'll be better off. Why don't you just pass around your object, instead of using the same instance.

You will still have to synch access if it is shared, even if you pass it around.

I'm just not really pro singleton, as they tend to lead for a need for more singletons which is inevitably what you should avoid.


As with many multi-threading questions, the answer is it depends. ;) read-only fields won't need extra synchronization while any read-write fields will most definitely require it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜