-1
我使用Singleton来存储对象的缓存,但每当我调用Singleton并添加到HashMap
时,它都没有值。使用HashMap的Android/Java Singleton不保留HashMap值
高速缓存是在方法的开始时检查(当大小为1),但再次增加了HashMap
时,它的大小为0。因此它的大小交替0
public class CachedObjects
{
static HashMap<String, Object> cachedObjects = new HashMap<>();
private static class InstanceHolder
{
private static final CachedObjects instance = new CachedObjects();
}
public static CachedObjects getInstance()
{
return CachedObjects.InstanceHolder.instance;
}
public void addObjectToCache(Object object)
{
cachedObjects.put(object.getTitle(), object);
}
public Object checkCacheForObject(String title)
{
Iterator it = cachedObjects.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pair = (Map.Entry) it.next();
if (pair.getKey().equals(title))
{
return (Object) pair.getValue();
}
it.remove(); // avoids a ConcurrentModificationException
}
return null;
}
}
当它被称为:
所有的public Object getObjectInfoFrom(String title)
{
Object cachedObjectCheck = CachedObjects.getInstance().checkCacheForObject(title);
// Size of HashMap is usually 1 here
if (cachedObjectCheck != null)
{
return cachedObjectCheck ;
}
// Lots of DB fetching here
Object object = new Object(DB details above);
CachedObjects.getInstance().addObjectToCache(object);
// The size of the HashMap always seems to be empty here
return object;
}
您需要同步访问地图。阅读javadoc中的hashmap,相关位在顶部以粗体显示。 –
1)不要实施一个单身人士,他们是邪恶的。如果你不得不依赖于一个使用Android框架提供的伪单身 - 比如'Application'对象。 2)你的代码没有意义。 InstanceHolder类没有任何用处,你的代码过于复杂。 3)我会小心内存泄漏,我不能看到所有可能导致内存泄漏的关键代码片段,但是代码的结构肯定看起来像内存泄漏可能就在眼前。 –
@XaverKapeller什么是单身人士的问题? – Vyacheslav