简体   繁体   中英

Concurrent Read - Reading different rows from same table by different java application instance in using jpa hibernate

I am writing a scheduler in spring boot, which will do the following action.

  1. read the 2 rows from a table (database - oracle)

  2. do some operation.

  3. Then update one field value of the rows read in step 1.

When I will run my application as two separate instances, 2 schedulers will run.

Which will make all the above steps repeated in 2 times.

My goal is if the schedule of the 1st instance is reading 2 rows at that time schedule of the 2nd instance to read next 2 rows, instead of the same row.

Please suggest any way to do this using JPA or in Java.

So let's have a look at your requirements:

  1. Each process instance should read two rows from some table
  2. A two-row-set worked on by one process should be off limits for any other process
  3. You don't want to wait for one process to finish the first two-row-set before the seconds process picks up its two rows

Now how to solve them?

  1. That's basic - you already have that, right?
  2. Could be done different ways, so let's first look at
  3. No blocking. That implies: Any of your processes being started has to be aware of the rows the other processes are working on

So you need some kind of "reservation" on the two rows the process is going to handle.

I'd handle it this way:

  • add a lock column into your table as this marker of "I'm currently worked at"
  • modify your selection query to ignore already locked columns AND
  • modify your selection query FOR UPDATE , preventing other processes from doing the same. (Yes, that IS blocking others, but only while you're at it)
  • Now update both rows to set the lock marker or your process
  • Do what you have to do
  • when you're ready for your step 3 (update field), reset lock marker.

You might want to take extra measures in terms of one process dying after setting lock-marker but before releasing them which could eventually lead to rows never processed - maybe us a timestamp value in lock column and select for lock based on reasonable time delta (process runs every 10 minutes - eveeything older than 30min is probably crashed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM