I need to "preload" some data from a database on servlet startup.
So I thought to create some cache e.g. using a HashMap or some similar synchronized version.
I also need to update the cache on database update changes.
So I thought to add some kind of "listener".
My question is: is this somehow available or do I have to actually implement it?
If yes what design pattern would be the best approach here?
Update:
No JPA or ORM used. But Spring is available
解决方案
Yes of course you can implement that
I'll draw a small architecture then ill explain it to u:
first of all , you can learn about Mappers here and TDGs here.
A mapper has a method called cacheAll() which calls and delegate to TDG's method cacheAll() which in its turn has a mission to get all rows from a table from the db( the rows you want to cache in the cache object).
so basically first you have to create a listener implementing "ServletContextListener"
which means its a listener for the whole servlet context, and inside its contextInitialized you have to call mp.fill(Mapper.cacheAll()), so it is sthg like ( this is general code, of course write it better and optimize it)
public class myServletContextListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
mp.fill(Mapper.cacheAll());
}
//
}
Don't forget to add your listener in web.xml:
myServletContextListener
so what this will do , is on startup of the server, will cache all record into a hashmap mp in a cache object.
As for updating cache based on database change, you will have to use observer pattern.
UPDATE
I forgot to mention, about the cache object, i assume you want it accessible for all users or your app, so you should code it as a singleton (singleton pattern), code like that:
public class cacheObject
{
private static Map cMap;
private static cacheObject cObject;
private cacheObject()
{
cMap = Mapper.cacheAll();
}
public static synchronized cacheObject getInstance()
{
if (cObject == null){
cObject = new cacheObject();
}
return cObject;
}
}
Also if the data that you want to cache can be changed by users, so make it a Threadlocal singleton.