Skip to content

Instantly share code, notes, and snippets.

@deveshmittal
Last active November 18, 2015 17:46
Show Gist options
  • Select an option

  • Save deveshmittal/19aba24a842ae4a8727b to your computer and use it in GitHub Desktop.

Select an option

Save deveshmittal/19aba24a842ae4a8727b to your computer and use it in GitHub Desktop.
How to write Double check Locking correctly
public class MyClass{
private volatile MyClass myClassObject;
public MyClass getInstance(){
MyClass helper = myClassObject;
// Optimisation for getting instance, if the helper has already been initialised return that.
if(helper == null){
synchronised(MyClass.this){
// Since synchronised block takes some time to initialise ,in the mean time another thread might have entered
// the synchronised block and initialised the helper variable. By ensuring that the myclassObject is volatile, we have established
// a happens-before functionality on the myClassObject.
// This means that a thread that comes later to another thread in the synchronised block erroneously, would not get the
// myClassObject to initialise as myClassObject only returns to the corresponding thread's helper variable after
// the thread that acquired the lock earlier has finished its' work.
// volatile objects are written in the main memory instead of the thread local space.
// In other version the threat was that new thread might see an initialised and unbaked version of helper as the
// other thread which has initialised the variable may be writing it in its' own memory, while the object is free
// to be returned as an initialised under process object.
helper = myClassObject;
if(helper == null){
myClassObject = helper = new MyClass();
}
}
return helper;
}
}
}
/*
Much of the reason to use this kind of pattern for a thread safe double check locking is due to the underlying Java Memory Model.
that entails the whole story of how the JVM actually interacts with the memory that resides natively in the Operating System.
Infact , JMM is the reason behind the Java's premise for "Write Once Run anywhere" guarantee.
Compilers can take the liberty of writing objects to CPU registers instead of RAM memory on a machine and also change the order
of sequence in which the program has been written to do some compiler optimisations.
Cache's may be in variance as in which writes commit to the main memory.
/*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment