0

Hey So I was examining the following code I found an online( https://javarevealed.wordpress.com/tag/initialization-on-demand-holder ) , which implements the Singelton design pattern using double checked locking like so:

public static volatile SingletonExample getSingletonInstance() {
        if (null == singletonInstance) {
            synchronized (SingletonExample.class){
                    if (null == singletonInstance) {
                         singletonInstance = new SingletonExample();
                     }
            }
        }
    return singletonInstance;
}

My question here is what is the point of having the volatile keyword in the method signature here? I thought the volatile modifier could be only be used on fields?

Any help would be great.

Thanks.

fulhamHead
  • 687
  • 1
  • 10
  • 23
  • 6
    Don't trust blog posts which can't even make it past Java syntax rules. – Marko Topolnik Oct 27 '14 at 11:20
  • `volatile` is not a valid modifier for methods, it can only be used for fields. Just try it and see what error the compiler gives you. Eclipse says: _"Illegal modifier for the method SingletonExample; only public, protected, private, abstract, static, final, synchronized, native & strictfp are permitted"_ – icza Oct 27 '14 at 11:24
  • ok cool lesson learned about blogs! thanks guys – fulhamHead Oct 27 '14 at 11:34

0 Answers0