Java: Lazy Initializing Singleton

前端 未结 5 662
情书的邮戳
情书的邮戳 2020-12-10 16:14

The pattern to create singletons seems to be something like:

public class Singleton {
    private static final Singleton instance = new Singleton();
    priv         


        
5条回答
  •  萌比男神i
    2020-12-10 16:54

    Double-checked locking is broken in every language, not just Java.

    I tend to eschew singletons, but you can use the holder pattern just fine if you need them, as recommended in Josh Bloch's Effective Java:

    public class Foo
    {
      static class Holder
      {
        static final Foo instance = new Foo();
      }
    
      public static Foo getInstance()
      {
        return Holder.instance;
      }
    
      private Foo()
      {
      }
    
      // ...
    }
    

    EDIT: Repaired the reference.

提交回复
热议问题