class MyClass
{
private static volatile Resource resource;
public static Resource getInstance()
{
if(resource == null)
volatile solves one issue that is visibility issue . If you are writing to one variable that is declared volatile then the value will be visible to other thread immediately. As we all know we have different level of cache in os L1, L2, L3 and if we write to a variable in one thread it is not guaranteed to be visible to other, so if we use volatile it writes to direct memory and is visible to others. But volatile does not solve the issue of atomicity i.e. int a; a++;
is not safe. AS there are three machine instructions associated to it.
I know you aren't asking about better solutions but this is definitely worth if you are looking for a lazy singleton solution.
Use a private static class to load the singleton. The class isn't loaded until invocation and so the reference isn't loaded until the class is. Class loading by implementation is thread-safe and you also incur very little overhead (in case you are doing repetitive volatile loads [which may still be cheap], this resolution always normal loads after initial construction).
class MyClass {
public static Resource getInstance() {
return ResourceLoader.RESOURCE;
}
private static final class ResourceLoader {
private static final Resource RESOURCE = new Resource();
}
}
I think, you should use syncronized
keyword before getInstance
definition.
For better performance you can use Double-checked locking pattern: