0

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!

Rodrigo Sasaki
  • 7,048
  • 4
  • 34
  • 49

1 Answers1

0

A better approach is to use the init method:

The servlet container calls the init method exactly once after instantiating the filter. The init method must complete successfully before the filter is asked to do any filtering work.

http://docs.oracle.com/javaee/5/api/javax/servlet/Filter.html#init(javax.servlet.FilterConfig)

public void init(FilterConfig filterConfig) throws ServletException {
     // read the file here, this method will be called only once
}
cahen
  • 15,807
  • 13
  • 47
  • 78