I coded a service to generate thumbnails for the images dynamically uploaded by users on my website. This is the way it works:
Get thumbnail:
- Check whether this thumbnail has been requested before
- If not, resize the original image to the requested size and cache it on the hard-drive
- Return the thumbnail cached on the hard-drive
Upload another image:
- Check whether this image has been uploaded before (e.g. a user may be updating his profile picture, the old one can be deleted)
- If yes, delete all the thumbnails of the old image
- Save/overwrite the new uploaded image
The problem is on point 2. when a user is requesting a thumbnail. What if two users are requesting the same thumbnail at the exact same time and it has not been resized before? Both the requests will tell the server to resize the original picture and save it on the hard-drive. Both the requests will attempt to write the same file on the hard-drive at the same time, causing obvious access problems.
How can I avoid this conflict in Spring MVC? All this thumbnail logic is managed inside a Spring controller like this:
@RequestMapping("/images/{width:\\d{1,10}}x{height:\\d{1,10}}/{subject:.+}.{ext:png|gif|jpg|PNG|GIF|JPG}")
public void thumbnail(HttpServletResponse response,
HttpServletRequest request,
@PathVariable("width") int width,
@PathVariable("height") int height,
@PathVariable("subject") String subject,
@PathVariable("ext") String ext) throws IOException
{
// ...
}