我正在尝试实现高性能线程安全缓存。这是我实现的代码。我不想要任何按需计算。我可以使用 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);
}
}