I have a simple servlet which merely serves some cached data back to the user. I also have a background thread which runs at fixed intervals to refresh the cached data. Is this a reasonable implementation?
@WebServlet("/CachingServlet")
public class CachingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static ScheduledExecutorService backgroundExecutor;
private static String cachedData = "";
public CachingServlet() {
super();
}
@Override
public void destroy() {
backgroundExecutor.shutdown();
super.destroy();
}
@Override
public void init() throws ServletException {
backgroundExecutor = Executors.newSingleThreadScheduledExecutor();
backgroundExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//implemention of fetchNewData() omitted for clarity
cachedData = fetchNewData();
}
}, 0, 1, TimeUnit.HOURS);
super.init();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(cachedData);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}