The singleton pattern in Java thread safety

  • 2020-04-01 03:39:46
  • OfStack


package net.kitbox.util;
/**
 *
 * @author lldy
 *
 */
public class Singleton {
    private Singleton(){
    }
    private static class SingletonHolder{
        private static Singleton  instance = new Singleton();
    }
    public static void method(){
        SingletonHolder.instance._method();
    }
    private void _method(){
        System.out.println("Singleton Method!");
    }
    public static void main(String[] args) {
        Singleton.method();
    }
}

This takes advantage of the classloader loading principle, where each class is loaded only once, so that the singleton is generated when its internal static class is loaded, and the process is thread-safe.

      The method() method encapsulates the private method of the internal singleton object and is used as the external interface so that it can be called as follows


Singleton.method();
//When used frequently, it is easier than the common singleton.getinstance ().method()

      Another way is to use enumeration to implement.

That's all for this article, I hope you enjoy it.


Related articles: