In Effective Java 2nd Edition Item 71, there's this code :
The author then comments
This code may appear a bit convoluted. In particular, the need for the local
variable result may be unclear. What this variable does is to ensure that field is
read only once in the common case where it’s already initialized. While not
strictly necessary, this may improve performance and is more elegant by the standards
applied to low-level concurrent programming. On my machine, the method
above is about 25 percent faster than the obvious version without a local variable.
I am having trouble understanding what he means by "read only"? Because to me "read only" translates to "immutable class".
And also how does the tempo variable helps achieve that. I'm hoping someone knowledgeable can clarify.
marwen Bakkar wrote:
How is field read more than once in the case where it's already initialized? And how is it 25x slower?
The field would be read first time in the first if statement and second time in the return statement. The field is declared volatile, which means it has to be refetched from memory every time it is accessed (roughly speaking, even more processing might be required to access volatile variables) and can not be stored into a register by the compiler. When copied to the local variable and then used in both statements (if and return), the register optimization can be done by the JVM.
25 percent faster means executing in about 0.75 of the time compared to the slower code, not (1/25) of the time.
Joined: Jan 28, 2010
Thank you very much! I am curious where did you learn about that?