Friday, 23 March 2012

Lazy initialization in java

Lazy initialization in java can be done in different ways.
  • In java we can use keyword volatile. This attribute on variable guarantees that any thread will see the most recently written value. From Java 5 version it can be used f.e. for lazy initialization in a multi-threaded environment.
  • Another way to do this is to use inner classes. This relies on the fact that inner classes are not loaded until they are referenced. So we can make assignment in the inner class.
  • We can also use synchronized block, but it is estimated to be 100 times slower then using volatile variable.
You can see more examples here: http://en.wikipedia.org/wiki/Double-checked_locking

No comments: