Inconsistency with ServletContextListener Usage in Spring Web Application

43 views Asked by At

I have a Spring Web application where I am implementing a ServletContextListener. I am setting a static JxBrowser Engine Object inside the contextInitialized method and setting it to null in the contextDestroyed method. This variable which was set in servlet context is being used in another class to create a browser object before using it to render html content in headless mode.

It works fine for some time and then it starts giving InvocationTargetException. As a temporary fix, I redeploy the application which again creates the engine object and stores it in Servlet Context.

I want to ask if setting something in ServletContext behaves inconsistently over time.

Here is the Sample code

@WebListener
public class SampleContextListener implements ServletContextListener {
    public static final Logger LOGGER = LogManager.getRootLogger();
    public static Engine engine = null;
    public static ServletContext context;
    public static String browserDirectory = "/tmp";

    @Override
    public void contextInitialized(ServletContextEvent event) {
                 
        engine = Engine.newInstance(EngineOptions.newBuilder(HARDWARE_ACCELERATED)
                .licenseKey("")
                .chromiumDir(Paths.get(browserDirectory))
                .build());
        LOGGER.info("Engine Initialized => " + engine);
        context = event.getServletContext();
        context.setAttribute("engine",engine);
        
    }
    //Run this before web application is destroyed
    @Override
    public void contextDestroyed(ServletContextEvent event) {
   
        try {
            context = null;
            if(engine != null && !engine.isClosed()) {
                engine.close();
                LOGGER.info("Engine Closed => " + engine);
            }
        } catch (IOException e) {
            LOGGER.info("Error While Deleting Browser Files: " + e.getMessage());
        }
    }
}



public class TestClass {
    
    public static final Logger LOGGER = LogManager.getRootLogger();
    public static final String TMP_DIRECTORY = "/tmp"
    
    public static String getEngine() {
        
        Engine engine = null;
        Browser browser = null;
        ServletContext servletContext = SampleContextListener.context;
        engine = (Engine) servletContext.getAttribute("engine");
        Browser browser = engine.newBrowser();
    }
}
0

There are 0 answers