-4

Consider the example:

class SomeClass{
     private Foo val;

     String getVal(){
           if(val == null){
                synchronized(this){
                      if(val ==null)
                           val = generateFoo();
                }
          }
     }

     Foo generateFoo(){
          //some code
          return new Foo();
     }
}

Is volatile in this case necessary?

Bober02
  • 15,034
  • 31
  • 92
  • 178

2 Answers2

0

According to The "Double-Checked Locking is Broken" Declaration it would appear that making it volatile is required.

JDK5 and later extends the semantics for volatile so that the system will not allow a write of a volatile to be reordered with respect to any previous read or write, and a read of a volatile cannot be reordered with respect to any following read or write. See this entry in Jeremy Manson's blog for more details.

With this change, the Double-Checked Locking idiom can be made to work by declaring the helper field to be volatile. This does not work under JDK4 and earlier.

However can I make a different suggestion?

Don't use singletons-the-design-pattern. Make it clear in the API that it should be a singleton. Allow users of your class to use it as a singleton, but to do so in way that makes sense for then, such as using Singleton-as-a-scope or in a Service Locator.

It will be easier to test, easier to work with and it will mean that the goddess who kills a kills kittens every time a singleton is used will not have to kill a kitten. Everyone is happy.

Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
0

no not necessary. You can go for AtomicReference.

AtomicReference atomicStringReference = new AtomicReference(val);

Check here: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

punya
  • 291
  • 3
  • 2