简体   繁体   English

高性能和线程安全的初始化块

[英]Performant and thread-safe initialization block

I just stumbled over the following piece of code and I'm wondering if there is a prettier alternative which has the same performance.我只是偶然发现了下面的一段代码,我想知道是否有一个具有相同性能的更漂亮的替代方案。

if (!isInitialized) {
    synchronized (this) {
        if (!isInitialized) {
            // Initialization code
            isInitialized = true;
        }
    }           
}

For sure, the outer if statement could be removed with no impact regarding thread safety.当然,可以删除外部 if 语句而不影响线程安全。 But it would have an impact to performance when multiple threads would call the code at the same time since the isInitialized check could only be done in one thread at once.但是当多个线程同时调用代码时会影响性能,因为 isInitialized 检查一次只能在一个线程中完成。

Doing the initialization in a static context is no option.在静态上下文中进行初始化是没有选择的。

This double-check-idiom (DCI or DCL for double check locking) is known for it's flaw because of instruction reordering.这种双重检查习语(DCI 或 DCL 用于双重检查锁定)因其指令重新排序而存在缺陷而闻名。

It only works if you declare the isInitialized variable as volatile, and only with jdk1.5+ (when volatile semantics and memory model got fixed).它仅在您将isInitialized变量声明为 volatile 时才有效,并且仅适用于 jdk1.5+(当 volatile 语义和内存模型得到修复时)。

Honestly, it's not that common anymore, with so much bad press...LOL.老实说,它不再那么常见了,有这么多的坏消息......大声笑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM