• Post Reply Bookmark Topic Watch Topic
  • New Topic

In defense of lazy initialization  RSS feed

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Brian's Goetz's new book Java concurrency in practise, he gives this example, to illustrate the problems with race conditions.

I want to argue that this is not an issue in certain cases:

1) When the object being constructed is lightweight. This is an example from j2me



2) When the value is an arithmetic constant that depends on final constants

Am I correct that we will never get threading errors in the 2x scenarios above ?

Thanks

Pho
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pretty much, yes. For the first case you may accidentally create two or more instances - but so what? It's true that you only need one, but it's not the end of the world if you accidentally create more than one. On the other hand, if the object being instantiated is lightweight - do you really need lazy instantiation at all? Why not just initialize it when it's declared?


As for your second point, yes: for any compile-time constant expression, threading issues are irrelevant since the value was determined at commpile time, and won't change.
[ July 28, 2006: Message edited by: Jim Yingst ]
 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim,

Good point about the lazy initialization for lightweight objects. Removing the redundant methods decreases the footprint of my app. Thanks

Pho
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!