Lazy initialization

Lazy initialization holder class idiom for static fields
Utilize JVM’s lazy class loading to create a lazy initialization technique that doesn’t require synchronization on the common code path.

public class ResourceFactory {
 private static class ResourceHolder {
  public static Resource resource=new Resource();
}
public static Resource getResource(){
 return ResourceHolder.resource;
}
}

JVM defers initializing the ResourceHolder class until it is actually used [1] and because Resource is initialized with a static initializer, no additional synchronization is required. The first call to getResource by any thread causes ResourceHolder to be loaded and initialized, at which time the initialization of the Resource happens through static initializer. A modern VM will synchronize field access only to initialize the class. Once the class is initialized, the VM will patch the code so that subsequent access to the field does not involve any testing or synchronization.

Continue reading

Advertisements