사용자 도구

사이트 도구


java:guava:cachebuilder

문서의 이전 판입니다!


Guava CacheBuilder

  • 메모리를 이용한 캐시 시스템을 간단히 구현할 수 있다.
  • Cache에서 값을 꺼낼 때 캐시에 값이 존재하는지를 먼저 검사하고 싶다면 Cache.asMap().get(“key”)로 값이 null인지 먼저 검사하면 된다.
  • null 값 자체를 리턴할 필요가 있다면 Guava Optional을 사용한다.

LoadingCache

  • LoadingCache 인스턴스는 객체 build시에 키에 해당하는 값을 로딩하는 로더를 지정해줘야한다. 권장.
LoadingCache<Key,Value> loadingCache = CacheBuilder.newBuilder()
  .some settings
  .build(new CacheLoader<Key, Value>() {
    @Override
    public Value load(Key cacheKey) throws Exception {
       ... blah blarh..
       return value;
    }
  });

com.google.common.cache.Cache

  • 그냥 Cache는 build시에 CacheLoader를 지정하지 않고, get할 때 값을 가져오는 로직을 넣을 수 있다.
Cache<Key, Value> cache = CacheBuilder.newBuilder()
    .maximumSize(1000)
    .build(); // look Ma, no CacheLoader
...
try {
  // If the key wasn't in the "easy to compute" group, we need to
  // do things the hard way.
  cache.get(key, new Callable<Value>() {
    @Override
    public Value call() throws AnyException {
      return doThingsTheHardWay(key);
    }
  });
} catch (ExecutionException e) {
  throw new OtherException(e.getCause());
}
java/guava/cachebuilder.1414126775.txt.gz · 마지막으로 수정됨: 2014/10/24 13:59 저자 kwon37xi