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.
This is an example of the initialisation-on-demand holder pattern. When the
Mathclass is loaded by the JVM, theRandominstance will not be constructed immediately. Instead that will only happen when therandom()method is called, at which point theRandomNumberGenreatorHolderclass will be loaded, and theRandomsingleton object constructed.Essentially the code is ensuring that the
Randomsingleton is created lazily.