eztam
eztam

Reputation: 3829

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. 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.

Doing the initialization in a static context is no option.

Upvotes: 1

Views: 65

Answers (1)

user2023577
user2023577

Reputation: 2083

This double-check-idiom (DCI or DCL for double check locking) is known for it's flaw because of instruction reordering.

It only works if you declare the isInitialized variable as volatile, and only with jdk1.5+ (when volatile semantics and memory model got fixed).

Honestly, it's not that common anymore, with so much bad press...LOL.

Upvotes: 1

Related Questions