boa noite a todos! estou estudando Singleton e me deparei com o seguinte código:
public class Singleton1 {
private volatile static Singleton1 uniqueStance;
private Singleton1() {}
public static Singleton1 getInstance()
{
if(uniqueStance == null)
{
synchronized(Singleton1.class)
{
if(uniqueStance == null)
{
uniqueStance = new Singleton1();
}
}
}
// por que são usados dois if's ?
// o primeiro já não verifica se a instância única é null ?
return uniqueStance;
}
}
Eu não entendi o porquê de ser necessário fazer essa dupla checagem e gostaria de saber se essa definição de volatile está correta:
“Volatile: In a multithreaded program sometimes two or more threads share
same variable. For efficiency each thread keeps its own private copy of the
shared variable and work on it. If you want to restrict the thread from
using your own private copy of the variable and let them use master copy of the
shared variable then modify variable using volatile modifier. In
short we can say that volatile modifier can not be cached by the threads.”
Obrigado!