使用Guava进行高性能的线程安全缓存 [英] Using Guava for high performance thread-safe caching

查看:1320
本文介绍了使用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;

公共类MemoryCache {

私有静态MemoryCache实例;
private Cache< String,Object>缓存

私有MemoryCache(int concurrencyLevel,int到期,int大小)引发IOException {

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

静态公共同步MemoryCache getInstance()引发IOException {
if(instance == null){
instance = new MemoryCache(10000,3600,1000000) ;
}
返回实例;
}

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

public void put(String key,Object obj){
cache.put(key,obj);
}
}


解决方案

番石榴是的,虽然我不确定将缓存包装在另一个对象中的意义是什么,但看起来还不错。 (此外, Cache.getIfPresent(key)完全等同于 Cache.asMap()。get(key)。 )


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);
    }
   }

解决方案

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).)

这篇关于使用Guava进行高性能的线程安全缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆