class MyClass
{
private static volatile Resource resource;
public static Resource getInstance()
{
if(resource == null)
volatile keyword guarantees that read and write to that variable are atomic.
According to the tutorial
Reads and writes are atomic for all variables declared volatile
Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.