Relying on synchronization in the class loader

Of all the various means of synchronization in the JVM, the most sophisticated is actually that of the class loader. Whenever a thread refers to a class encountered for the first time, some relatively complex logic kicks in to ensure that two threads don't simultaneously try to load and/or instantiate the same class. It is possible to take advantage of this logic to implement lazy initialisation of singletons:

public class Factory {
  private static final Factory instance = new Factory();

  public static Factory getInstance() {
    return instance;
  }

  // Declare the constructor private so nobody else can instantiate this class
  private Factory() {}
}

With this pattern, we ensure that a maximum of one instance of Factory is created. And we alleviate the need to synchronize in the getInstance() method. The first time that this method is called will be when the Factory class is loaded and initialised; in doing so, the class loader will automatically handle synchronization.

On the next pages, we'll look at: