Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 485
Rols Avatar asked Jan 24 '26 09:01

Rols


2 Answers

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}
like image 112
BalusC Avatar answered Jan 25 '26 22:01

BalusC


Have your servlet occasionally check the file for changes with a timer.

Googling "Java monitor file for changes" will present many examples, one of which you can find here: http://www.devdaily.com/java/jwarehouse/jforum/src/net/jforum/util/FileMonitor.java.shtml

like image 41
Brian Roach Avatar answered Jan 25 '26 22:01

Brian Roach