How to implement thread-safe lazy initialization?

后端 未结 12 830
一整个雨季
一整个雨季 2020-11-28 04:13

What are some recommended approaches to achieving thread-safe lazy initialization? For instance,

// Not thread-safe
public Foo getI         


        
12条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 04:46

    Try to defined the method which gets an instance as synchronized:

    public synchronized Foo getInstance(){
       if(INSTANCE == null){
        INSTANCE = new Foo();
      }
    
      return INSTANCE;
     }
    

    Or use a variable:

    private static final String LOCK = "LOCK";
    public synchronized Foo getInstance(){
      synchronized(LOCK){
         if(INSTANCE == null){
           INSTANCE = new Foo();
         }
      }
      return INSTANCE;
     }
    

提交回复
热议问题