3

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...
    }
jinghui70
  • 31
  • 2
  • No. It doesn't change a thing here. The method call adds nothing: thus it changes nothing. –  Oct 11 '12 at 06:24
  • No, the function does not add anything but it still is not broken. – Tobias Ritzau Oct 11 '12 at 06:26
  • 1
    @TobiasRitzau I believe it still is broken, actually. It would need to be a volatile field AFAIK to be guaranteed under the Java 5 MM. See the linked article. –  Oct 11 '12 at 06:27
  • @pst, you are right. sorry... – Tobias Ritzau Oct 11 '12 at 06:29
  • 2
    Folks, please read the linked article through to the end, don't just skim it. The helper field needs to be declared volatile. The private function is useless. As of JSE5, it would work then. – Christian Schlichtherle Oct 11 '12 at 06:32

1 Answers1

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

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.

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

    public static Helper getHelper() {
        return HelperHolder.helper;
    }
}
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72