开发者

Instance variables and threading

I have a class like the below and am wondering, will this be thread-safe or can the main thread and the Loader thread possibly have their own copys of the mCache and therefore the get(..) method fail to retreive anything from the cache as it was added in the loader thread? Do i need to mark this volatile?

Thanks!!

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));
        }
    }
}


The variable is final, so it will be visible to all threads before the constructor (empty in this case) returns.


volatile means that each thread will not keep a cache of the value of the field. If you were able to write to the mCache field then you would declare it volatile if you wanted to be sure that another thread got the new value when reading the field immediately after it was set by another thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜