任何单例模式早期实例化的问题
我使用惰性实例化单例模式遇到了一些问题
参考:http:// www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html。
同样,使用早期实例化的单例模式是否存在任何问题?
I came across some issues using lazy instantiated singleton pattern
Reference: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.
Similarly is there any issues in using early instantiated singleton pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是大约十年前写的。自 2004 年以来,最简单的单例模式是使用一个带有一个实例的
enum
。This was written about ten years ago. Since 2004, the simplest Singleton pattern is to use an
enum
, with one instance.这个想法似乎是实例化单例可能成本高昂,因此如果尽早完成(也许对于很多单例),可能会导致应用程序启动时长时间暂停,而惰性实例化会分散延迟并可能避免它们如果并不总是需要单例,则完全可以。
这对于大量应用程序来说真的是一个问题吗?我非常确定它不是,并且有关延迟实例化单例的博客文章和问题的数量与其实际用途完全不成比例。我同样确信所有这些关注给很多人留下了这样的印象:这就是单例必须如何实现,并导致他们在直接的半热切实例化单例就可以完全正常的地方选择不必要的复杂解决方案。
那么为什么这个问题会受到如此多的关注呢?我怀疑这部分是因为它说明了与一般并发代码相关的 Java 内存模型的一些细节,部分是因为它是一个聪明的游戏。
The idea seems to be that instantiating the singleton may be costly, so if it's done early (and perhaps for a lot of singletons) it may lead to a long pause when the application starts, whereas lazy instatiation spreads the delays around and may avoid them entirely if a singleton is not always needed.
Is this really an issue for a significant number of applications? I am very certain it is not, and the amount of blog posts and questions about lazily-instantiated singletons is completely out of proportion to its practical usefulness. I am equally certain all this attention has given a lot of people the impression that this is how Singletons must be implemented and caused them to choose an unnecessarily complex solution in places where a straightforward semi-eagerly instantiated Singleton would have been perfectly fine.
So why does this issue get so much attention? I suspect that it's partially the fact that it illustrates some finer points of the Java memory model that are relevant for concurrent code in general, and partially a game of smartassery.