我有一個像下面的類,我想知道,這將是線程安全的,或者主線程和Loader
線程可能有自己的mCache
副本,因此get(..)方法無法從緩存中檢索任何內容,因爲它是在加載程序線程中添加的?我需要標記這個volatile
?實例變量和線程
謝謝!
public class StackExample
{
private final ConcurrentHashMap<String, SoftReference<Bitmap>> mCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>();
private addToCache(String key, Bitmap bitmap)
{
mCache.put(key, bitmap);
}
private Bitmap getBitmap(String key)
{
if(mCache.contains(key))
{
return mCache.get(key);
}
else
{
//add to loading queue
}
}
private class Loader extends Thread
{
@Override
public void run()
{
...//check loading queue and load some images here
mCache.put(keyString, new SoftReference<Bitmap>(loadedBitmap));
}
}
}
您將只對所有線程都具有唯一的* mCache *,但您的代碼仍然沒有正確同步。你*可以*輸入兩次(或多於)* *添加到加載隊列*你的代碼的一部分爲同一個*鍵*雖然從你的例子中並不完全清楚* getBitmap *從哪裏調用(它顯然是私有的!?)。 – SyntaxT3rr0r
btw +1對你的問題和羞恥的人誰upvoted Jon Skeet的一個線路的答案,也沒有upvoting很好的問題。 – SyntaxT3rr0r
謝謝!是的,只是一個簡單的例子,我知道你的意思是關於get方法:) – Dori