lundi 23 février 2015

Design: Object with single use?

Context


I have a class called ImageLoader.


When I call ImageLoader's getPicture( pictureID ), if the picture is not cached, I store pictureID in an instance variable, create a new thread which eventually calls my callback() function in this same ImageLoader class. callback() then uses this pictureID as the key to cache the picture.


Problem


Do you see the pickle? If I call getPicture( somePictureID ) twice in a row, and the callback() function for the first call hasn't happened yet, I will overwrite the previous pictureID which the callback() function will use.


Now I know you're thinking, why don't I just add a little synchronization on the variable to make it thread-safe?


Because who knows how long the thread querying the picture will take, and that could really slow down the whole process of loading multiple images.


How I'm Thinking of Solving It


So my bright idea is to create in inner class that servers as a slave and only has a single use. I execute some function in this slave class once, and I never reuse the object.


Question


Is this an appropriate approach to solving this kind of problem? I feel like this might fall into some pattern I'm not aware of. If I'm totally off the mark with this one, can you suggest another solution?


Aucun commentaire:

Enregistrer un commentaire