Lets look at classical double check
class Foo {
private volatile Foo singleton = null;
public Foo getFooSingleton() {
if (singleton == null) {
synchronized(this) {
if (singleton == null)
singleton = new Foo();
}
}
return singleton;
}
}
Volatile modifire guaranties that value of "singleton" variable will be seen correctly in all threads. But really do I need this in current example? I think no. So - that's how I see this program runs in the worst way - when changes made by one thread are not seen by other.
- thread one enteres synchronized section and creates singleton
- thread two enteres synchronized, synchronize its current stack values (now he sees
singleton != null
), makes second check and exits synchronized section.
So. Everything works even without volatile declaration, and even better =)