ITeye博客

java double checked locking broken

wangyanlong0107 · 2018-09-15 01:56 · java · 编程语言 · Markdown

// Double-check idiom for lazy initialization of instance fields

private volatile FieldType field;

FieldType getField() {

    FieldType result = field;

    if (result == null) { // First check (no locking)

        synchronized(this) {

            result = field;

            if (result == null) // Second check (with locking)

                field = result = computeFieldValue();

        }

    }

    return result;

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。