如何在单独的线程中进行单例的急切初始化?
我想对多个单例进行热切初始化,但初始化可能需要几分钟的时间,因此我希望初始化发生在单独的线程上。有办法做到这一点吗?
I would like to do eager initialization of multiple singletons but the initialization can take on the order of minutes so I would like the initialization to happen on a separate thread. Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://tembrel.blogspot.com/2009/11/concurrently -initialized-singletons-in.html
http://tembrel.blogspot.com/2009/11/concurrently-initialized-singletons-in.html
当然,只需启动一个辅助线程并让它完成即可。最简单的方法是使用 SingletonHolder 并执行任何导致辅助线程中初始化的操作。如果其他线程在初始化完成之前尝试访问它,则会阻塞,因此一切正常。
Sure, just start an auxiliary Thread and let it do it. The easiest way is using SingletonHolder and doing anything which causes the initialization in the auxiliary Thread. Other threads will block if they try to access it before the initialization finishes, so everything works fine.