aspose file tools*
The moose likes Java in General and the fly likes About a lazy initialization technique Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "About a lazy initialization technique" Watch "About a lazy initialization technique" New topic
Author

About a lazy initialization technique

marwen Bakkar
Ranch Hand

Joined: Jan 28, 2010
Posts: 84
Hello,

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.

Thanks.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4546
    
    5

Blame the English language. Introducing a line break might help. The word 'read' is the past tense (rhymes with red)

What this variable does is to ensure that field is read (accessed)
only once (not twice or more) in the common case where it’s already initialized.


luck, db
There are no new questions, but there may be new answers.
marwen Bakkar
Ranch Hand

Joined: Jan 28, 2010
Posts: 84
My bad :/ Thanks for pointing this out! But still, if we had the version without the local variable:



How is field read more than once in the case where it's already initialized? And how is it 25x slower?
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3610
    
  60

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.
marwen Bakkar
Ranch Hand

Joined: Jan 28, 2010
Posts: 84
Thank you very much! I am curious where did you learn about that?
 
 
subject: About a lazy initialization technique