Java ReentrantLock by ID

154 views Asked by At

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.

2

There are 2 answers

2
Cliser On BEST ANSWER

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.

3
cedar On

Cliser you are almost there just one thing you can do is, write repositories of lock that are mapped against ID in your case.

We can use HashMap to main these locks against ID in java.

Steps as below:

  1. in acquire method.. push ID into our hashmap and acquire a lock.
  2. in the release method first you will look if ID exists in hashmap. if it does release the lock if conditions holds true

Let me know if this helps.