使用Guava进行高性能的线程安全缓存

sys*_*oot 17 caching guava

我正在尝试实现高性能的线程安全缓存.这是我实现的代码.我不想要任何随需应变计算.我可以使用cache.asMap()并安全地检索值吗?即使缓存设置为softValues?

  import java.io.IOException;
  import java.util.concurrent.ConcurrentMap;
  import java.util.concurrent.ExecutionException;
  import java.util.concurrent.TimeUnit;
  import java.util.concurrent.TimeoutException;

  import com.google.common.cache.Cache;
  import com.google.common.cache.CacheBuilder;

  public class MemoryCache {

    private static MemoryCache instance;
    private Cache<String, Object> cache;

    private MemoryCache(int concurrencyLevel, int expiration, int size) throws IOException {

        cache = CacheBuilder.newBuilder().concurrencyLevel(concurrencyLevel).maximumSize(size).softValues()
            .expireAfterWrite(expiration, TimeUnit.SECONDS).build();
    }

    static public synchronized MemoryCache getInstance() throws IOException {
        if (instance == null) {
               instance = new MemoryCache(10000, 3600,1000000);
        }
        return instance;
    }

    public Object get(String key) {
        ConcurrentMap<String,Object> map =cache.asMap();
        return map.get(key);
    }

    public void put(String key, Object obj) {
        cache.put(key, obj);
    }
   }
Run Code Online (Sandbox Code Playgroud)

Lou*_*man 29

番石榴贡献者:

是的,这看起来很好,虽然我不确定将缓存包装在另一个对象中的意义.(另外,Cache.getIfPresent(key)完全等同于Cache.asMap().get(key).)

  • @GaryGauh是的. (10认同)

Fra*_*eau 6

如果你想要高性能,为什么不静态地实现Cache而不是使用synchronized getInstance()?