0

I want to locking the program for some races of database operations.

I would use a lock in jdbc, for example I want to query something :

 synchronized (mylock) {
   if(mydata != null) return;
   getDataFromDatabase();
}

But now for a reactor program, I think it's not good to use a lock, because it will block the thread.

How to deal such races?

I finally use a lock as following.

if(mydata != null) return Mono.just(mydata);
lock.lock();
if(mydata != null) return Mono.just(mydata);
return myRepository.findAll()
            .collect(xxx)
            .doFinally(signalType->lock.unlock());

Ander
  • 66
  • 6
  • How many connections do you expect at once? How long does the database task take? If there are not many connections, and the database task doesn't take long then there are no issues using synchronized with only one database connection at a time. You will likely not even notice that some events are waiting. I don't know your needs, but if you want a more comprehensive solution then consider restructuring your database into parts, and simply create a lock on the individual parts that need it (not the whole database), that way you can still make multiple queries as necessary. – sorifiend Aug 02 '22 at 01:30
  • @sorifiend Using a lock is ok for my case, I just find a better way to implement this semantics in reactive scenario. – Ander Aug 03 '22 at 08:23
  • 1
    If you want to limit the number of requests to the database, you could switch to use a different reactor scheduler and specify the number of tasks/threads that it can use. There is also a single thread scheduler available if you only want to run one query at a time. – Erik Finnman Aug 16 '22 at 10:00

0 Answers0