Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About a lazy initialization technique

 
marwen Bakkar
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5125
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marwen Bakkar
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much! I am curious where did you learn about that?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic