Java双重检查锁定,此代码是否有效?

时间:2022-11-06 06:51:52

I have read The "Double-Checked Locking is Broken" Declaration. But I wonder if i create the object by a function, will that be ok?

我读过“双重锁定已破损”声明。但我想知道我是否通过函数创建对象,这样可以吗?

    class Foo { 
      private Helper helper = null;
      public Helper getHelper() {
        if (helper == null) 
          synchronized(this) {
            if (helper == null) 
              helper = createHelper();
          }    
        return helper;
      }
      private Helper createHelper() {
         return new Helper();
      }
      // other functions and members...
    }

1 个解决方案

#1


5  

No it will not make a difference adding a function will not make any difference. And your function is doing nothing.

不,它不会有所作为添加一个功能不会有任何区别。你的功能无所作为。

However if you declare it as volatile it will start working from Java 1.5

但是,如果将其声明为volatile,它将从Java 1.5开始工作

private volatile Helper helper = null;

One of the correct way of Lazy initialization in java is Initialization-on-demand holder idiom .This relies on the fact that inner classes are not loaded until they are referenced.

在Java中进行Lazy初始化的正确方法之一是Initialization-on-demand holder习惯用法。这依赖于内部类在被引用之前不加载的事实。

class Foo {
    private static class HelperHolder {
        public static Helper helper = new Helper();
    }

    public static Helper getHelper() {
        return HelperHolder.helper;
    }
}

#1


5  

No it will not make a difference adding a function will not make any difference. And your function is doing nothing.

不,它不会有所作为添加一个功能不会有任何区别。你的功能无所作为。

However if you declare it as volatile it will start working from Java 1.5

但是,如果将其声明为volatile,它将从Java 1.5开始工作

private volatile Helper helper = null;

One of the correct way of Lazy initialization in java is Initialization-on-demand holder idiom .This relies on the fact that inner classes are not loaded until they are referenced.

在Java中进行Lazy初始化的正确方法之一是Initialization-on-demand holder习惯用法。这依赖于内部类在被引用之前不加载的事实。

class Foo {
    private static class HelperHolder {
        public static Helper helper = new Helper();
    }

    public static Helper getHelper() {
        return HelperHolder.helper;
    }
}