How does Distributed Locking work if the database information is loaded into the JVM memory before the lock is done?

Viewed 113

I was assigned to a new project and found this:

A scheduler is supposed to take some rows from a database(based on a flag), update some information on them and after that save it to the database again. After the information is retrieved as List, each element of the list is passed to a method(let's call it "processData") that does certain processing. The body of the method acquires a lock from the RedisLockRegistry based on the Id of the MessageDb, does a certain processing and finally releases the lock.

Now let's assume two instances of the app want to access the same resources in the Database exactly at the same time.

My question is: Since a lock prevents two(or more) instances of an app accessing the same database resource in the same time in order to avoid data corruption, what is the behavior going to be since the lock is acquired only after both of the instances have retrieved the information from the database?

From my understanding of how locks work it will be like this:

  1. Both App Instances(I1, I2) retrieve the same data in the same time as List
  2. Both I1 and I2 call the "processData()" method foreach element of the retrieved list (remember the processData() body: obtainLock, process, unlock)
  3. Let's say that I1 manages to acquire the lock for one of the elements, it does the processing, updates the element in the database and unlocks.
  4. I2 gets the lock for the same element since I1 released it and it can now do the changes. But how are the changes going to be done since now the state of the element in the database is different from the state of the element that I2 has in memory (Because of the I1 update)
0 Answers
Related