devutility.internal.cache.MemoryCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of devutility.internal Show documentation
Show all versions of devutility.internal Show documentation
Utilities for Java development
package devutility.internal.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import devutility.internal.lang.StringUtils;
import devutility.internal.util.CollectionUtils;
public class MemoryCache {
/**
* Container
*/
private static volatile Map container = new HashMap<>();
/**
* Set entry in memory.
* @param entry: Entry object.
* @return boolean
*/
public static boolean set(CacheEntry entry) {
if (entry == null || StringUtils.isNullOrEmpty(entry.getKey()) || entry.getValue() == null) {
return false;
}
if (entry.getValue() instanceof Collection) {
Collection> collection = Collection.class.cast(entry.getValue());
if (CollectionUtils.isNullOrEmpty(collection)) {
return false;
}
}
synchronized (MemoryCache.class) {
container.put(entry.getKey(), entry);
}
return true;
}
public static boolean set(String key, Object value, int expireSeconds) {
CacheEntry entry = new CacheEntry(key, value, expireSeconds);
return set(entry);
}
public static boolean set(String key, Object value) {
return set(key, value, 0);
}
public static Object get(String key) {
CacheEntry entry = container.get(key);
if (entry == null) {
return null;
}
if (entry.expired()) {
del(key);
return null;
}
return entry.getValue();
}
public static T get(String key, Class clazz) {
Object value = get(key);
if (value == null) {
return null;
}
return clazz.cast(value);
}
public static List getList(String key) {
Object value = get(key);
if (value == null || !(value instanceof ArrayList)) {
return new ArrayList<>();
}
@SuppressWarnings("unchecked")
List list = (ArrayList) value;
return list;
}
public static List getList(String key, Class clazz) {
Object value = get(key);
if (value == null || !(value instanceof ArrayList)) {
return new ArrayList<>();
}
@SuppressWarnings("unchecked")
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy