what happens if more than one thread tries to access singleton object

廉价感情. 提交于 2019-12-21 04:42:15

问题


Not during instantiation, but once instantiation of singleton object is done, what will happen if two or more threads are trying to access the same singleton object? Especially in the case where the singleton object takes lot of time to process the request (say 1 min)... In this case, if for ex., 5 threads try to access the same singleton object, what will the result be?

Additional question: normally when should we go for the singleton pattern and when should we avoid it?


回答1:


Unless synchronization (locking) is being performed within the Singleton, the answer is this: it's a free-for-all.

Though the Singleton ensures that only one instance of an object is used when requested, the pattern itself doesn't inherently provide any form of thread safety. This is left up to the implementer.

In the specific case you cited (with a long running method), it would be critical to synchronize access to any method that uses class or object-level variables. Failure to do so would, in all likelihood, lead to race conditions.

Good luck!




回答2:


The general rule of thumb i use for Singletons is that it should not affect the running code, and have no side-effects. Essentially for me, in my projects this translates into some kind of logging functionality, or static value lookup (ie. loading some common data from a database once and storing it for reference so it doesn't have to be read in everytime its needed).




回答3:


A singleton is no different than any other object other than there is only one instance. What happens when you try to access it will largely depend on what the accessing threads are attempting (ie read vs write) and what kind of data your singleton is holding.




回答4:


The answer to your question as it is, is "it really depends". What kind of singleton? i.e. what does it do, and how does it do it? And in what language?

The reality is that the singleton patter)n only dictates and enforces that you can only have one instance of a certain object. In of itself it does not say anything about multiple threads accessing that object.

So, if coded right (with thread synchronization implemented correctly) there is no reason why it shouldn't behave correctly - even if the requests to the object take a really long time to process!




回答5:


Then you need thread safe implementation of singleton pattern.

Find this article useful for the same which describes most of the multi-threading scenario of singleton pattern.

HTH!



来源:https://stackoverflow.com/questions/1322506/what-happens-if-more-than-one-thread-tries-to-access-singleton-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!