trending-topics/src/main/java/org/gcube/portlets/user/topics/server/cache/TopicsCacheImpl.java

78 lines
1.7 KiB
Java

package org.gcube.portlets.user.topics.server.cache;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;
/**
* TopTopics cache: the key of each value is the scope
* @author Costantino Perciante at ISTI-CNR
* (costantino.perciante@isti.cnr.it)
*/
public class TopicsCacheImpl implements CacheInterface<String, ArrayList<String>> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TopicsCacheImpl.class);
private static TopicsCacheImpl instance = new TopicsCacheImpl();
/**
* The hashmap
*/
private Map<String, CacheValueBean<ArrayList<String>>> cacheMap;
/**
* Cache entry expires after EXPIRED_AFTER ms
*/
private static final long EXPIRED_AFTER = 1000 * 60 * 2;
/**
* private constructor
*/
private TopicsCacheImpl(){
this.cacheMap = new HashMap<String, CacheValueBean<ArrayList<String>>>();
}
/**
* Retrieve the current cache instance object
* @return
*/
public static TopicsCacheImpl getCacheInstance(){
return instance;
}
@Override
public ArrayList<String> get(String key) {
if(cacheMap.containsKey(key)){
CacheValueBean<ArrayList<String>> bean = cacheMap.get(key);
if(CacheUtilities.expired(bean.getTTL(), EXPIRED_AFTER)){
cacheMap.remove(key);
logger.debug("TopTopics for scope " + key + "expired, return null");
}
else
return bean.getValue();
}
return null;
}
@Override
public boolean insert(String key, ArrayList<String> value) {
CacheValueBean<ArrayList<String>> newBean = new CacheValueBean<ArrayList<String>>(value, System.currentTimeMillis());
if(cacheMap.containsKey(key))
cacheMap.remove(key);
cacheMap.put(key, newBean);
return true;
}
}