I need a cached map in my Java code. The map is loaded from DB and needs reloaded periodically from DB (for all of the data in the map). Since we can't import any new package now. Is there any existing function in google's guava package or code example?
It is better if the map is implemented as thread safe. But it is still OK if it is not but simple enough.
The "LoadingCache" is kind of what I like but it doesn't have data initialization method for me to put the data into the map at the beginning. And it needs to reach the DB for everytime "get" comes after the map expired.
Thank you!
Some sample codes may help here:
public interface AToBMapper
{
public static final String DEFAULT_B_NAME = "DEFAULT";
public String getBForA(final String a);
}
public class AToBMapperImpl implements AToBMapper
{
private final SomeDAO dao;
private Map<String, String> cachedMap;
public AToBMapperImpl(final SomeDAO dao)
{
this.dao = dao;
cachedMap = new HashMap<String, String>();
}
public String getBForA(final String a)
{
// if the map is not initialized, initialize it with the data
// if the map is expired, refresh all the data in the map
// return the mapped B for A (if there is no mapping for A, return the "DEFAULT")
}
private Map<String, String> getTheData(final List<String> listOfB)
{
Map<String, String> newData = dao.getAToBMapping(listOfB);
}
}