Skip to main content

JSR 292 Goodness: lazy Singleton Pattern

Posted by forax on November 5, 2010 at 3:51 AM PDT

The idea of the lazy Singleton Pattern is to initialize a static field only when needed and not during the initialization of the class. The code for that pattern is this one:

  private static Database database;
  public static Database getDatabase() {
    synchronized (DCL.class) {
      if (database == null) {
        database = new Database();
      return database;

In that case, you pay the synchronization cost each time you access to the variable. Note that it's far from obvious that in a real application this synchronization cost is significant,
but for the rest of this blog, let say that this cost is not acceptable.

As you probably already know the Double-Checked Locking idiom (DCL) is broken.
The recommanded idiom is to declare another class and to use natural lazy loading of the class in Java. 

  static class Lazy {
    private static final Database database = new Database();

  public static Database getDatabase() {
    return Lazy.database;

In this blog post, I want to show you another way to solve that problem using invokedynamic. The invokedynamic instruction has a powerful initialization mechanism, the first time an invokedynamic instruction is seen a bootstrap method (a factory method) associated to the invokedynamic instruction is called to get a method handle (a safe function pointer) that will be called for the current call and the next calls.

public static Database getDatabase() {
    try {
      return (Database);
    } catch(Throwable t) {
      throw new RuntimeException(t);
  private static Database identity(Database o) {
    return o;
  private static CallSite bootstrap(Class<?> declaringClass, String name, MethodType type) {
    Database db;
    synchronized (DCL.class) {
      db = database;
      if (db == null) {
        db = database = new Database();
    CallSite cs = new CallSite();
    return cs;
  private static final MethodHandle identity;
  static {
    identity = MethodHandles.lookup().findStatic(DCL.class,"identity",
        MethodType.methodType(Database.class, Database.class));

The static init block registers the boostrap method "boostrap" that will be called the first time the invokedynamic instruction in getDatabase() is executed. The JSR 292 allows the boostrap method to be executed by more than one thread concurrently by example if a thread is prempted in the middle of the boostrap method before registering the call site object another thread can run the boostrap method. But the JSR 292 guarantees that the invokedynamic call site will be bounded to only one CallSite object. That's why here the boostrap method synchronizes the access to the field database to be sure that only one Database object will be created. After that, it creates a method handle that will always return the same constant. As the time of writing (jdk7b116), creating a method handle that returns a constant is not that simple. The next iteration of the spec introduces a new method handle combiner MethodHandles.constant() that can be used like this:

    return new ConstantCallSite(MethodHandles.constant(db));

The next iteration of the spec also contains a new class ConstantCallSite to tell the VM that the target method handle will never change.
Also, I register one boostrap method for all invokedynamic instructions of the current class, this approach is deprecated and it's now possible to have one boostrap methods by invokedynamic instruction. But there is not yet a Java syntax to specify a boostrap method per invokedynamic. We're working on this.

The main advantage of using invokedynamic instead of using the class initialization idiom is that after boostraping the reference to the database is considered as a real constant, i.e like if it was declared as a static final field. In fact even a little bit more "constant" because if the field type is not a primitive or a string you can change the value of a static final field using reflection in Java.

To run the code with jdk7b116 :

   java -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic DCL


Related Topics >>


JSR 292 Goodness: lazy

The article you refer to is quite old, wasn't this fixed in Java 5?

JSR 292 Goodness: lazy

Declaring the variable volatile is a way to fix the DCL.
BTW, this is the pattern used by Scala to implement the keyword lazy.

But this pattern introduces a volatile read and JITs aren't good to optimize such thing :(


JSR 292 Goodness: lazy

If the pattern by itself introduces a volatile read, are we not better off simply marking the variable volatile ?

There seems to be a lot of code in there just to lazy instantiate a variable. In fact there is more code to lazy instantiate the variable, than there is to define the SIngleton itself :D

If the future holds a more concise call that would accomplish the same, that would be great.

JSR 292 Goodness: lazy

Nice post , just to add
While writing Singleton class you also need to consider following points :
1) Lazy initialization
2) Early initialization
3) Serialization
4) Many ClassLoaders
5) Cloning

Why String is immutable in Java