任何单例模式早期实例化的问题

发布于 2024-12-19 01:13:49 字数 243 浏览 1 评论 0原文

我使用惰性实例化单例模式遇到了一些问题

参考: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

通知家属抬走 2024-12-26 01:13:49

这是大约十年前写的。自 2004 年以来,最简单的单例模式是使用一个带有一个实例的enum

enum Singleton {
    INSTANCE;
}

This was written about ten years ago. Since 2004, the simplest Singleton pattern is to use an enum, with one instance.

enum Singleton {
    INSTANCE;
}
纵山崖 2024-12-26 01:13:49

这个想法似乎是实例化单例可能成本高昂,因此如果尽早完成(也许对于很多单例),可能会导致应用程序启动时长时间暂停,而惰性实例化会分散延迟并可能避免它们如果并不总是需要单例,则完全可以。

这对于大量应用程序来说真的是一个问题吗?我非常确定它不是,并且有关延迟实例化单例的博客文章和问题的数量与其实际用途完全不成比例。我同样确信所有这些关注给很多人留下了这样的印象:这就是单例必须如何实现,并导致他们在直接的半热切实例化单例就可以完全正常的地方选择不必要的复杂解决方案。

那么为什么这个问题会受到如此多的关注呢?我怀疑这部分是因为它说明了与一般并发代码相关的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文