Here are the requirements for the problem:
- java web application running in Tomcat 7
- The initialization code needs to talk to an external database
- The external database might not be available during start-up of the application
- The application start-up can not fail otherwise tomcat will mark the application as not running and will not send the application any requests. Instead the application should start-up accept requests and if it finds that the app specific initialization is not complete it should try to complete it during the request processing.
I am trying to use the servlet filter below to solve the problem. and I have following questions.
- Is this Servlet filter thread safe, will it execute the initialization code only once?
- Is there a way to solve this problem without using a servlet filter?
- Is there a better way to solve this problem?
package com.exmaple;
@WebFilter("/*")
public class InitFilter implements Filter
{
private volatile boolean initialized = false;
public void destroy() {
System.out.println("InitFilter.destroy()");
}
// is this method thread safe and will only execute the init code once
// and will cause all requests to wait until initialization code is executed
// thread code
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("InitFilter.doFilter()");
if (initialized == false) {
synchronized (this) {
// do expensive initialization work here
initialized = true;
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("InitFilter.init()");
}
}