Search code examples
javaservletscronreload

how to re-initialize java servlet on text file change


I have a servlet that pulls data from a text file during initialization. Now I am updating that text file with a cron job(say everyday at 10am) and want to reinitialize the servlet every time this particular file changes.

Second approach I can follow is to sync the reinitialization of the servlet to my cron job.

Kindly suggest on how to go about implementing either of the above two approaches.

thanks.


Solution

  • Don't get hold of it as instance variable of the servlet. Create a ServletContextListener which stores it in the application scope and runs a thread which updates it on every interval with help of ScheduledExecutorService.

    E.g.

    @WebListener
    public class Config implements ServletContextListener {
    
        private ScheduledExecutorService scheduler;
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            Data data = new Data(); // Your class which reads and holds data upon construction.
            event.getServletContext().setAttribute("data", data);
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.scheduleAtFixedRate(new Reloader(data), 0, 1, TimeUnit.DAYS);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            scheduler.shutdownNow();
        }
    
    }
    

    with this runnable

    public class Reloader implements Runnable {
    
        private Data data;
    
        public Reloader(Data data) {
            this.data = data;
        }
    
        @Override
        public void run() {
            data.reload();
        }
    
    }
    

    It's accessible a random servlet.

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        Data data = (Data) getServletContext().getAttribute("data");
        // ...
    }
    

    And even in a random JSP.

    ${data.something}