语境
我有一个叫做ImageLoader的类.
当我调用ImageLoader的getPicture(pictureID)时,如果未缓存图片,则将pictureID存储在实例变量中,创建一个新线程,该线程最终在同一ImageLoader类中调用我的callback()函数.然后callback()使用此pictureID作为缓存图片的键.
问题
你看到泡菜了吗?
如果我连续两次调用getPicture(somePictureID),并且第一次调用的callback()函数尚未发生,那么我将覆盖callback()函数将使用的先前的pictureID. (如果您仍然看不到泡菜,请参见下面的代码.)
现在我知道您在想,为什么不只在变量上添加一点同步以使其成为线程安全的呢?
因为谁知道查询图片的线程将花费多长时间,这确实会减慢加载多张图片的整个过程.
我如何解决它
因此,我的明智之举是创建一个内部类,该内部类将服务器作为从属服务器,并且只能使用一次.我在此从属类中执行了一次功能,并且从不重用该对象.
题
这是解决此类问题的合适方法吗?我觉得这可能会陷入我不了解的某种模式.如果我对此一无所知,您能建议另一种解决方案吗?
简码
//the instance variable with a race condition
private int pictureID
//loads the image associated with the pictureID
public void getPicture( int pictureID )
{
Bitmap bitmap = cache.get( pictureID );
if ( bitmap != null )
{
//load image
return;
}
int post_params[] = { pictureID, /* more parameters */ };
this.pictureID = pictureID; //PROBLEM: race condition!
new HttpRequest( this ).execute( post_params ); //starts new thread and queries server
}
//gets called when the query finishes, json contains my image
public void callback( JSONObject json )
{
Bitmap bitmap = getBitmap( json ); //made up method to simplify code
cache.put( this.pictureID, bitmap ); //PROBLEM: race condition!
//load image
}