1

I am running java application with multiple threads those will query from oracle database and if condition meets it will update row. But there are high chances that multiple threads gets same status for a row and then multiple thread try to update same row.

Lets say if status is "ACCEPTED" for any row then update it to "PROCESSING" status and then start processing, But processing should be done by only one thread who updated this record.

One approach is I query database and if status is "ACCEPTED" then update record, I need to write synchronized java method, but that will block multi-threading. So I wanted to use sql way for this situation.

Hibernate update method return type is void. So there is no way I can find if row got updated now or it was already updated. Is there any Select for Update or any locking thing in hibernate that can help me in this situation.

Sohan Badaya
  • 365
  • 4
  • 15

2 Answers2

0

You can very well make use of Optimistic Locking through @Version.

Please look at the post below:

Optimistic Locking by concrete (Java) example

Community
  • 1
  • 1
shankarsh15
  • 1,947
  • 1
  • 11
  • 16
0

I think that your question is related to How to properly handle two threads updating the same row in a database

On top of this I woud say on top of the answer provided by @shankarsh that if you want to use a Query and not the entitymanager or the hibernate session you need to include the version field in your query like this:

update t.columntoUpdate,version = version + 1 from yourEntity where yourcondition and version = :version

This way the update will succeed only for a particular version and all the concurent updates will not update anything.

Alexander Petrov
  • 9,204
  • 31
  • 70