Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

 Have a Kindle? Sign up to the newsletter  Follow follow the author on Twitter
 RECOMMEND THIS SITE TO FRIENDS/COLLEAGUES:

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:


Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Javamex UK 2012. All rights reserved.