-2

I came across the below code as part of creating a singleton using DoubleLocking

public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    while(instance == null){
        synchronized (ThreadSafeSingleton.class) {
            while(instance == null){
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}

What is the significance of using while loop instead of the usual if block? Is it due to some JMM issues which might affect the singleton creation in Multi Threaded Environment?

ghostrider
  • 1,722
  • 1
  • 17
  • 29
  • 3
    That's just unnecessary. It will only loop once, so it's equivalent to if. – Andy Turner Jul 10 '20 at 15:25
  • 2
    The thing about double-checked locking is it can be quite hard to get right (to the extent that even Josh Bloch got it wrong in the first printing of *Effective Java* 3rd Ed), so people do... weird things, "just in case". – Andy Turner Jul 10 '20 at 15:29
  • 1
    Side bar: [What is so bad about singletons?](https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) – Andrew S Jul 10 '20 at 15:30

1 Answers1

2

Using a while loop there is unnecessary.

Each of the loops will only execute zero or one times, so they are equivalent to if.

Andy Turner
  • 122,430
  • 10
  • 138
  • 216