Is there a way to ensure that a class's static initialization is performed at runtime, and not on the first access of said class?
I am asking because I am currently using a library(of useful tools across multiple projects) but some of them take a reasonable amount of time to initialize. This leads to noticeable lag on the first access of said class, which is not good.
I do understand I can manually initialize it by adding a static method that I call myself at runtime, which does nothing, to force initialize that class, but if there is something I can do to ensure it will be initialized without manually calling an initialization method, that would be much better.
This is what I mean:
Utility Class:
public class Utility {
public static final Map mapping = new HashMap();
static {
//Read file and fill in mappings
}
}
Main Class:
public class Main {
public void main(String[] args){
//
//Do things for a while
//
Object something =
Utility.mapping.get("else"); //Lag spike occurs here as the
//static initialization was
//only just now run
}
}
This is what I currently do to force it, but requires me to call it manually:
Utility Class:
public class Utility {
public static final Map mapping = new HashMap();
static {
//Read file and fill in mappings
}
public static void init(){}
}
Main Class:
public class Main {
public void main(String[] args){
Utility.init(); //Lag occurs here, where it belongs
//
//Do things for a while
//
Object something =
Utility.mapping.get("else"); //No lag spike now
}
}
performed at runtime- how runtime is different from "first access"?