i've been taught that in java static init block will be called before any instance of object will be created, but I faced a situation while playing with old singleton pattern (not to discuss why it's good or bad pattern). In the example below i have two implementations of lazy singleton and second breaks order in which ctor & static init blocks are called.
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SingletonDemo {
static class demo1 {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
static class Singleton {
public static Singleton instance() {
return SingletonHolder.INSTANCE;
}
static {
log.info("Singleton1$static");
}
public Singleton() {
log.info("Singleton1$init");
}
}
}
static class demo2 {
static class SingletonHolder {
public static Singleton instance() {
return Singleton.INSTANCE;
}
}
static class Singleton {
static final Singleton INSTANCE = new Singleton();
static {
log.info("Singleton2$static");
}
public Singleton() {
log.info("Singleton2$init");
}
}
}
public static void main(String[] args) {
demo1.Singleton.instance();
demo2.SingletonHolder.instance();
}
}
and output is as follows:
04:50:36.815 [main] INFO SingletonDemo - Singleton1$static
04:50:36.831 [main] INFO SingletonDemo - Singleton1$init
04:50:36.831 [main] INFO SingletonDemo - Singleton2$init
04:50:36.831 [main] INFO SingletonDemo - Singleton2$static
so the question is why ?