Guy Segal
Guy Segal

Reputation: 981

Database concurrency - handling out of sync objects

I am using a DAL service to retrive data from the database.

Lets observe to simplest case where I retrieve one object from the database.

After retrieving that object I am doing some changes to its properties according to some business logic, and than I want to update the object in the persistent database.

However, some other client (maybe even one I am not aware that exists) changed the state of the underline object in the database, and I identify this when I am trying to update.

What should I do in this case?

Should I throw an exception?

Should I try to update only the fields that I changed?

Should I lock that table for writing while I am performing bussiness logic based on the persistant data?

Guy

Upvotes: 1

Views: 150

Answers (2)

Amol Sonawane
Amol Sonawane

Reputation: 1130

This is very subjective and it depends on what exactly you are trying to.

Should I throw an exception?

  • You should if you are not expectig the update by other user. For instance, your software is trying to book a seat which has been already booked by somebody, you will throw say SeatAlreadyBookedException and handle that appropriately by logging or showing proper message

Should I try to update only the fields that I changed?

  • You can do that if you have not used the existing state to make an update or you want your changes to be final changes overriding any changes already done by other users. For instance, if want to update a new date for the dead-line for a project.

Should I lock that table for writing while I am performing bussiness logic based on the persistant data?

  • Locking a table will affect the overall throughput. Your application logic should take of these transactions and maintan the data integrity.

Upvotes: 0

Yosi Dahari
Yosi Dahari

Reputation: 7009

I think what you should do depends on what you are trying to achieve. Your main options as i see it:

  • lock beforehand - main pros & cons - occupying the database until you commit, much more simple.

  • don't lock beforehand, merge in case someone else updated it - main disadvantage - merging can be very complex

I would go with the first one, but i would try to minimize the locking time (i.e i would figure out what's all the changes i want to do prior to locking the object).

Any way i don't think this is an exceptional case.. so i won't go with throwing exception.

Upvotes: 3

Related Questions