I feel like this is probably already answered somewhere, but I couldn't find it or maybe I'm not using the right keywords.
What I want to do is an initialize a value in a Servlet Filter
with as little blocking as possible. I am by no means an expert in threads, so here is what I came up with:
private static Object getObject() {
if(OBJECT == null) {
synchronized (MyClass.class) {
InputStream is = getInputStream("path_to_file");
OBJECT = loadObject(is);
}
}
return OBJECT;
}
This method is used within the Servlet Filter, which will be called by multiple threads at once. I want to make sure that I load this when it is needed, and not on the init
method.
My question is, is this thread safe? Once it is initialized I think it'll be good, but I want to make sure that it works when it's being initialized.
PS: Please redirect me to any question that already answers this if they exist. Thanks!