I have a problem to refresh or reload an application scoped managed bean. It behaves as cached data bean. So once data is changed on db side, i want to reload the the list in the bean. Is there anyway to refresh/reload the list, say once a day based on given time? Thanks
Asked
Active
Viewed 1.0k times
1 Answers
14
Just add a method to the aplication scoped bean which does exactly that.
public void reload() {
list = dao.list();
}
Then grab/inject this bean in another bean and call the method.
data.reload();
Update sorry, I overlooked the "once a day" bit. You mean automatic reloading in the background? This is best to be achieved by a background thread which is managed by ScheduledExecutorService
. Create a ServletContextListener
like follows:
@WebListener
public class Config implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent event) {
Reloader reloader = new Reloader(event.getServletContext());
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(reloader, 1, 1, TimeUnit.DAYS);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}
Where the class Reloader
look like this (assuming that the managed bean name is data
)
public class Reloader implements Runnable {
private ServletContext context;
public Reloader(ServletContext context) {
this.context = context;
}
@Override
public void run() {
Data data = (Data) context.getAttribute("data");
if (data != null) {
data.reload();
}
}
}

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
1You're welcome. You have however to be extremely careful with managing threads yourself in a servletcontainer. The `scheduler.shutdownNow();` bit in `contextDestroyed()` is very important. You may consider delegating the thread management job to the servletcontainer, if it supports it. JBoss has for example Quartz for this, Glassfish has for example `WorkManager` for this. In Tomcat, the above example is your best bet. – BalusC Feb 04 '11 at 14:34
-
@BalusC I have the same need. I implemented this in my application. The only one problem is that in `Reloader` method `run()` my bean is always null. Can u give me a hint please – leostiw Jul 12 '13 at 09:01