oncurrentHashMap<>缓存不同的key
在开发过程需要对bitmap对象进行临时缓存,也看了写网的说法,于是参考一些文档,使用了ConcurrentHashMap<>来实现,因此做个笔记;
不多解释了,直接上代码:
public class CacheBitmap {
//
private static ConcurrentHashMap<String, Bitmap> icMap = new ConcurrentHashMap<>();
/**
* 通过setKeyOfBitmap缓存对象
*
* @param key
* @return
*/
public static void setKeyOfBitmap(String key, Bitmap bitmap) {
key = getCacheKey(key);
// 如果缓冲区没有当前对应的key,缓存。
if (!icMap.containsKey(key)) {
// 缓存不同的key和对应的bitmp
initCache(key, bitmap);
}
}
/**
* 初始化缓存
*
* @param key
*/
private static void initCache(String key, Bitmap bitmap) {
// Data query results are cached
icMap.put(key, bitmap);
}
/**
*拼接对应的key缓存
*
* @param key
* @return
*/
private static String getCacheKey(String key) {
return Thread.currentThread().getId() + "-" + key;
}
/**
* 删除缓存
*
* @param key
*/
public static void removeCache(String key) {
icMap.remove(getCacheKey(key));
}
public Bitmap getBitmap(String key) {
key = getCacheKey(key);
// 如果在缓冲区帐户中有对应的key,返回
if (icMap.containsKey(key)) {
return icMap.get(key);
}
return icMap.get(key);
}
}
以上也是做个小记,望有所帮助…