实例变量和线程

发布于 2024-11-17 12:14:32 字数 927 浏览 1 评论 0原文

我有一个如下所示的类,我想知道这是否是线程安全的,或者主线程和 Loader 线程是否可能拥有自己的 mCache 副本,因此get(..) 方法无法从缓存中检索任何内容,因为它被添加到加载器线程中?我需要标记这个易失性吗?

谢谢!!

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愁杀 2024-11-24 12:14:32

该变量是最终变量,因此在构造函数(在本例中为空)返回之前,它对所有线程都可见。

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

若沐 2024-11-24 12:14:32

易失性表示每个线程不会保留字段值的缓存。如果您能够写入 mCache 字段,那么如果您想确保另一个线程在另一个线程设置该字段后立即读取该字段时获得新值,则可以将其声明为易失性。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文