实例变量和线程
我有一个如下所示的类,我想知道这是否是线程安全的,或者主线程和 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该变量是最终变量,因此在构造函数(在本例中为空)返回之前,它对所有线程都可见。
The variable is final, so it will be visible to all threads before the constructor (empty in this case) returns.
易失性
表示每个线程不会保留字段值的缓存。如果您能够写入 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.