多线程环境中的单例
使用单例时,如果类具有实例字段,那么当多个线程可能使用单例时,您是否应该小心? (并且字段是可变的,它们的值可以更改)
我没有尝试过,但从理论上讲,答案似乎是肯定的,您需要同步(或跳过单例)
when using singletons, if the class has instance fields should you be careful 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您从多个线程(或进程)访问对象(或相同的可变数据)时,您将需要某种同步。无论是单例还是任何其他“非单例”对象都没有区别。
另一个问题是,在单例的情况下,单例的创建,如果这是第一次使用时创建的,那么第一次可能会同时用于不同的线程,因此您还需要同步单例的创建。
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.