延迟加载的单例:双重检查锁定与需求持有者习语的初始化 [英] Lazy-loaded singleton: Double-checked locking vs Initialization on demand holder idiom
问题描述
我需要在并发环境中延迟加载资源。加载资源的代码只应执行一次。
两者重复选中锁定(使用JRE 5+和volatile关键字)和按需持有者标识初始化< a>似乎适合工作。
只要看看代码,需求持有者习语的初始化看起来更干净,更有效率(但嘿,我在这里猜)。不过,我必须照顾和记录每一个单身人士的模式。至少对我来说,很难理解为什么代码是这样写的...
我的问题是:哪种方法更好?为什么?
如果你的答案是none。
我可以使用CDI,而不强加它对我的整个项目的使用?
添加另一个,可能更干净的选项。我建议使用枚举变体:
I have a requirement to lazy-load resources in a concurrent environment. The code to load the resources should be executed only once.
Both Double-checked locking (using JRE 5+ and the volatile keyword) and Initialization on demand holder idiom seems to fit the job well.
Just by looking at the code, Initialization on demand holder idiom seems cleaner and more efficient (but hey, I'm guessing here). Still, I will have to take care and document the pattern at every one of my Singletons. At least to me, It would be hard to understand why code was written like this on the spot...
My question here is: Which approach s is better? And why? If your answer is none. How would you tackle this requirement in a Java SE environment?
Alternatives
Could I use CDI for this without imposing it's use over my entire project? Any articles out there?
To add another, perhaps cleaner, option. I suggest the enum variation:
这篇关于延迟加载的单例:双重检查锁定与需求持有者习语的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!