Lets say I have a multi-threaded application that needs to resize some image files. I don’t want multiple thread to be able to resize the same image at the same time and overwrite each others result and corrupt the file, but to maximise concurrency I do want multiple threads to be able to resize different images at the same time.
What would be the best approach for a thread to acquire a lock on a specific image rather than simply synchronizing an entire block of code?
Use an fixed thread
ExecutorServiceand have a thread which submits all of the images into the service to be processed. As long as you don’t submit the same image twice you won’t have a problem.You could also have a thread which feeds the “todo”
BlockingQueuefor the other threads to consume. So then you have one thread that controls which images the threads work on so there would be no locks necessary.Another way to do it would be to use a
ConcurrentHashMapand have each threadputIfAbsentand then only consume the image only if it worked.