Cache

LoadingCache

Case1

  1. LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
  2. .maximumSize(1000)
  3. .expireAfterWrite(10, TimeUnit.MINUTES)
  4. .removalListener(MY_LISTENER)
  5. .build(
  6. new CacheLoader<Key, Graph>() {
  7. @Override
  8. public Graph load(Key key) throws AnyException {
  9. return createExpensiveGraph(key);
  10. }
  11. });

Case2

  1. LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
  2. .maximumSize(1000)
  3. .build(
  4. new CacheLoader<Key, Graph>() {
  5. public Graph load(Key key) throws AnyException {
  6. return createExpensiveGraph(key);
  7. }
  8. });
  9. ...
  10. try {
  11. return graphs.get(key);
  12. } catch (ExecutionException e) {
  13. throw new OtherException(e.getCause());
  14. }

From a Callable

  1. Cache<Key, Value> cache = CacheBuilder.newBuilder()
  2. .maximumSize(1000)
  3. .build(); // look Ma, no CacheLoader
  4. ...
  5. try {
  6. // If the key wasn't in the "easy to compute" group, we need to
  7. // do things the hard way.
  8. cache.get(key, new Callable<Value>() {
  9. @Override
  10. public Value call() throws AnyException {
  11. return doThingsTheHardWay(key);
  12. }
  13. });
  14. } catch (ExecutionException e) {
  15. throw new OtherException(e.getCause());
  16. }

参考文档

https://github.com/google/guava/wiki/CachesExplained