Search code examples
javamultithreadingreentrantlock

Java ReentrantLock by ID


I'm working on Java and I have a "batch" procedure, with multiple objects, and each one of them does something on the db (mainly updates). I want some of them to wait each other, but only if a specific condition is encountered. To be precise, some of them may update the same entity, and Java gives an OptimisticLockException in that case, but some others may update other entities, so they don't have to wait. I would like to create a ReentrantLock (or something that works like that) with a specific ID (in this case, the entity ID), and only the ones which have the same ID may wait until it is unlocked, while the others can execute their code freely.

I don't know if the request is clear, as english is not my first language, sorry. But, I would appreciate if someone can help me!

Thanks in advance.


Solution

  • The idea of the HashMap was correct, but I was calling the .lock() method, while I needed to call the .wait() method only for the threads that needed to wait, while the others could just go on. I created a HashMap<Long, ReentrantLock>, having the entity ID as the key and a new instance of the ReentrantLock as a value. When the "main" thread has finished, it calls the .notify() method, which randomly releases one of the waiting threads (and that's what I want), which (again) releases another thread when finished, and so on.