0

I am confused about this , double-checked locking need volatile.

public class someClass {

public volatile static uniqueInstance = null;

public static someClass getInstance() {
        if(uniqueInstance == null) {
            synchronized(someClass.class) {
                if(uniqueInstance == null) {
                    uniqueInstance = new someClass();
                }
            }
        }
        return uniqueInstance;
    }

The reason is this , Why is volatile used in this example of double checked locking. according this explains, the reason is that be "initialized" with partially constructed object.

The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. This results in Thread B failing because it is using a partially constructed version of instance.

But why Thread B will see the latest value , Thread B will read the old value before synchronized block finished.

Each thread may see a different snapshot, so the fact that one thread reads a variable inside a synchronized block does not mean that another thread which reads the variable without synchronization will see the same state thanks in advance.

thanks in advance

tanghuailong
  • 11
  • 1
  • 4
  • IIRC, volatile is used to prevent certain optimizations that would not be threadsafe. Also I don't think it is advisable to lock on the class object itself because it is visible to other code for other uses and may this may lead to deadlocks. I could well be wrong about this, as my experience is primarily with. Net, where we haven't had to use primitive approaches as double-check locking for about a decade – Aluan Haddad Sep 30 '18 at 06:10
  • Double checked locking has been so popular in the last ten years or so. e.g. if you want a singleton you can just do `enum someClass { uniqueInstance }` which is shorter, cleaner and also thread safe. – Peter Lawrey Oct 01 '18 at 18:57

0 Answers0