How can a local variable be assigned here?

I read about blocking double check out Effective Java.
The code performs the following actions:

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;  
}    

It says that use resultseems unnecessary, but actually ensures that it fieldis read only once in the normal case, when it is already initialized.
But I don’t get it. What is the difference with executing if(field == null)directly?
I do not understand why it if (result == null)is different, not to mention the best, as indicated.
Any help understand this please?

+5
source share
2 answers

, / , . result ( ).

.

initializaton on demand, , . http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

... :

: ( ) ( , ..). , . volatile //cpus/memory, ( , ..). jvm ( hotspot , , ),

+4

( ):

, , , . , . 25% , .

, p. 284 71: " Java 2nd Edition".

: , . , . , .

. Java Concurrency , 3.1.4: " ".

+5

All Articles