A Digital Life

My Notebook

View My GitHub Profile

  • About
  • 5 December 2016

    Lazy-loading a Singleton Instance

    by kerner1000

    A thread-save version of lazy-loading a singleton instance. The instantiation of the singleton is delegated to the JVM which makes this approach fully thread-save – without explicit synchronization.

    public class Singleton {
     
        // class-private singleton constructor
        private Singleton() {}
     
        private static class InstanceHolder {
            private static final Singleton instance = new Singleton();
        }
     
        public static Singleton getInstance() {
            return InstanceHolder.instance;
        }
    }
    

    Further reading:

    tags: singleton - concurrency - software design patterns - software development - Java