I want to create a singleton object of a third party caching library (ThirdPartyKVStore
). But I don't want to reference this class all over the place from where I want to access the cache. To address this, I created a wrapper CacheManager
which is managing the lifecycle of ThirdPartyKVStore
. Does it look ok?
public class CacheManager {
private static ThirdPartyKVStore thirdPartyCache = null;
private static volatile CacheManager cacheManager = null;
private CacheManager(){
}
public static CacheManager getConnection(CacheConfig cacheConfig) {
if (cacheManager == null) {
synchronized (CacheManager.class) {
if (cacheManager == null) {
try {
thirdPartyCache = new ThirdPartyKVStore(cacheConfig);
cacheManager = new CacheManager();
} catch (Throwable e) {
logger.error("Fn=getConnection Msg=Cache_Initialization_Error_Occurred.", e);
}
}
}
}
return cacheManager;
}
public static void closeCacheConnection(){
if(thirdPartyCache != null){
thirdPartyCache.shutdown();
}
}
public <T> T getCacheData(String key){
T cachedObject = null;
String cachedStr = null;
Entry<String> e = thirdPartyCache.get(key);
if(e != null){
cachedStr = e.getPayload();
}
if (cachedStr != null) {
TypeToken<T> typeToken = new TypeToken<T>() {};
cachedObject = deserializeStr2POJO(cachedStr, typeToken);
}
return cachedObject;
}
public <T> void setCacheData(String key, T t){
if (thirdPartyCache != null) {
try {
Entry<String> e = new Entry.Builder<String>(new Gson()
.toJson(t))
.withVersion(DEFAULT_VERSION)
.withApplication(DEFAULT_APP)
.build();
thirdPartyCache.set(key, e, Integer.MAX_VALUE);
} catch (Exception e) {
}
}
}
}