Google Guava's CacheLoader loadAll() method Implementation Issues

10,910

Your getAllGraphsFromDatabase method should be fetching the values from the underlying data store. The LoadingCache implementation handles adding the returned values to the map for you.

I think your loading method should look like:

private Map<Key, Graph> getAllGraphsFromDatabase(Iterable<? extends key> keys)
{
  final List<Graph> lListOfGraph = //resultset got from DB Call

  final Map<Key, Graph> map = new HashMap<Key, Graph>(listOfGraph.size());
  for (final Graph graph : lListOfGraph)
    map.put(graph.getKey(), graph);

  return map;
}
Share:
10,910
Anand Sanghvi
Author by

Anand Sanghvi

I am currently with TCS working on cloud erp in solution development team working mainly with java and guava library's.

Updated on June 27, 2022

Comments

  • Anand Sanghvi
    Anand Sanghvi almost 2 years

    I am interested in knowing what is the effective way of loadAll method implementation introduced in google guava 11.0 library.

    Here is the following code that describes load all method implementation extended
    as per the example from CachesExplained

    LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder().maximumSize(1000)
    .refreshAfterWrite(1, TimeUnit.MINUTES)
    .build(
       new CacheLoader<Key, Graph>() {
         public Graph load(Key key) { // no checked exception
           return getGraphFromDatabase(key);
         }
    
         public Map<Key, Graph> loadAll(Iterable<? extends K> keys) {
             return getAllGraphsFromDatabase(keys);
         }
       }
    );
    
    private Map<Key, Graph> getAllGraphsFromDatabase(Iterable<? extends key> keys)
    {
      lListOfGraph = //resultset got from DB Call
      for (lCount = 0; lCount < lListOfGraph.size(); lCount++)
      {
         lGraph = (Graph)lListOfGraph.get(lCount).get(0);
         graphs.asMap().put((key , lGraph);
      }
      return (Map<key, Graph>) graphs;
    }
    

    Here return type that is Map throws error java.lang.ClassCastException:com.google.common.cache.LocalCache$LocalLoadingCache cannot be cast to java.util.Map (Knowing the fact that Loading Cache object can not be of type Map)

    If this is not the correct way of implementation of using LoadingCache then How is the data injected in LoadingCache's Component so that it can be used as Cache.