Using Guava for high performance thread-safe cachi

2019-04-18 15:15发布

I am trying to implement a high performance thread-safe caching. Here is the code I have implemented. I don't want any on demand computing. Can I use cache.asMap() and retrieve the value safely? Even if the cache is set to have 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);
    }
   }

标签: caching guava
2条回答
Root(大扎)
2楼-- · 2019-04-18 15:32

If you want high performance, why don't you instanciate the Cache statically instead of using a synchronized getInstance()?

查看更多
小情绪 Triste *
3楼-- · 2019-04-18 15:42

Guava contributor here:

Yes, that looks just fine, although I'm not sure what the point is of wrapping the cache in another object. (Also, Cache.getIfPresent(key) is fully equivalent to Cache.asMap().get(key).)

查看更多
登录 后发表回答