sabu
sabu

Reputation: 2077

How to have concurrency isolation in a spring app using jdbc template

I am using spring and jdbctemplate. (no hibernate). I have table with a status.

If the status is OPEN, it can be CLOSED and certain processing will be done. But it can be closed only once.

Now I have a situation, that multiple threads or request can come to same code block where I check the status of row.

T data = getJdbcTemplate().query()...
// Multiple request/threads can come here at same point. 
if ( data.getStatus() == "OPEN"){
   // business logic
}

How can I handle such scenario?

Upvotes: 0

Views: 138

Answers (1)

rmalchow
rmalchow

Reputation: 2769

if you're using something like mysql or pgsql, then you can do:

   UPDATE table WHERE id="id" AND status = "OPEN"

and check the number of affected rows (from JdbcTemplate.upate()). mysql and mariadb for example guarantee that this update only happens once. the second concurrent thread will receive zero updated rows.

then, you can do your processing.


edit:

This behaviour is part of what the RDMS guarantees (see, for example, https://en.wikipedia.org/wiki/ACID)

Also, in case you're wandering what happens when processing fails - the pattern I ususally use is to set the status to something like "PENDING", possibly set a date there as well, and reset the state if it is stuck on "PENDING" too long. This, of course, can be modified to be flagged to go through some kind of manual check if necessary.

Upvotes: 1

Related Questions