Inicialização lazy sem locks
Substitua double-checked locking por StableValue para singletons lazy.
Comparação de Código
✕ Java 8
class Config {
private static volatile Config inst;
static Config get() {
if (inst == null) {
synchronized (Config.class) {
if (inst == null)
inst = load();
}
}
return inst;
}
}
✓ Java 25 (Preview)
class Config {
private static final
StableValue<Config> INST =
StableValue.of(Config::load);
static Config get() {
return INST.get();
}
}
Viu um problema com este código? Nos avise.
Por que a forma moderna ganha
Sem boilerplate
Sem volatile, synchronized ou verificação dupla de null.
Leituras mais rápidas
A JVM pode fazer constant-fold após a inicialização.
Comprovadamente correto
Sem bugs sutis de ordenação — a JVM cuida disso.
Abordagem Antiga
synchronized + volatile
Abordagem Moderna
StableValue
Desde o JDK
25
Dificuldade
Avançado
Suporte JDK
Inicialização lazy sem locks
Preview
Preview no JDK 25 (JEP 502, StableValue). Requer --enable-preview.
Como funciona
StableValue encapsula o padrão de inicialização lazy com segurança de threads correta. A JVM pode otimizar o caminho de leitura após a inicialização, tornando-o potencialmente mais rápido que leituras volatile.
Documentação Relacionada