Search code examples
javajava-8design-decisions

Design decision - What is the use/advantage of separate RandomNumberGeneratorHolder class in Math.java?


So I was going through the Math.java source code and I found that there is a holder class created to hold the randomNumberGenerator static variable. Here is the relevant piece of code.

public final class Math {
 // other methods.
 public static double random() {
   return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
 }

 private static final class RandomNumberGeneratorHolder {
   static final Random randomNumberGenerator = new Random();
 }
}

IMO, We could have simply declared the randomNumberGenerator as private static final inside the Math class itself.

My question is, Is there any advantage of creating a separate holder class for this? Or it is just a personal preference.


Solution

  • This is an example of the initialisation-on-demand holder pattern. When the Math class is loaded by the JVM, the Random instance will not be constructed immediately. Instead that will only happen when the random() method is called, at which point the RandomNumberGenreatorHolder class will be loaded, and the Random singleton object constructed.

    Essentially the code is ensuring that the Random singleton is created lazily.