Reputation: 27425
Java 7
I'm reading J. Bloch's effective Java and now I'm at the section about initializing field laziliy. He introudce the so called double-check idiom as follows:
public static void main(String[] args){
Test t = new Test();
long now = System.nanoTime();
t.getT();
long invokationTime = System.nanoTime() - now;
System.out.println(invokationTime); //Prints 3299 averagely
}
private static class Test{
private volatile Test field;
public Test getT(){
Test result = field; // <----- Note the local variable here
if(result != null){
synchronized (this) {
result = field;
if (result == null)
field = result = new Test();
}
}
return result;
}
}
He gave the following explanation of using the local variable:
What this variable does is to ensure that field is read only once in the common case where it’s already initialized.
Now, let's consider the following code:
public static void main(String[] args){
Test t = new Test();
long now = System.nanoTime();
t.getT();
long invokationTime = System.nanoTime() - now;
System.out.println(invokationTime); //Prints 3101 averagely
}
private static class Test{
private volatile Test field;
public Test getT(){
if(field != null){
synchronized (this) {
if (field == null)
field = new Test();
}
}
return field;
}
}
On my machine, the second lazy-init method is even faster. But on ideone's machine they took approximately 7985 and 10630 like J. Bloch said. So is it worth to use such local variables for optimization? As far as I coould figure out, the costs of reading and writing variables are almost equal.
So we should worry about it only if the method consist mostly of such lightweight operation, right?
Upvotes: 0
Views: 32
Reputation: 7576
It's sort of worth it because you already decided that eager loading and synchronization are both too expensive. But really, it's almost certainly not. The cases where you actually need double-checked locking code tend to be in non-locking data structures and things. Good designs for performant code tend to push that into isolated places so you're not shooting yourself in the foot every time you touch the code.
Upvotes: 1