Skip to content

Instantly share code, notes, and snippets.

@avraampiperidis
Created August 20, 2016 06:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avraampiperidis/b14cd6c70fc3fed38f7cb6b93e42d020 to your computer and use it in GitHub Desktop.
Save avraampiperidis/b14cd6c70fc3fed38f7cb6b93e42d020 to your computer and use it in GitHub Desktop.
Android LruCache Wrapper. easy to use between activities
import android.support.annotation.NonNull;
import android.support.v4.util.LruCache;
public class AppCache<T> {
private final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
private final int cacheSize = maxMemory / 6;
private LruCache<String,T> cache;
private static volatile AppCache appCache;
private AppCache() {
if(cache == null) {
cache = new LruCache<String,T>(cacheSize);
}
}
public static <T> T getInstance() {
if(appCache == null) {
synchronized (AppCache.class) {
if(appCache == null) {
appCache = new AppCache();
return (T)appCache;
}
}
}
return (T)appCache;
}
public LruCache<String,T> getCache() {
return cache;
}
public void put(@NonNull String key,T t) {
if(cache == null) {
cache = new LruCache<String,T>(cacheSize);
}
cache.put(key,t);
}
public <T> T get(@NonNull String key) {
if(key == null) {
return null;
}
if(cache == null) {
return null;
}
return (T)cache.get(key);
}
public <T> T remove(String key) {
return (T)cache.remove(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment