Concurrency – Handling or Preventing Conflicts in a Multi-User System

concurrencylocks

I have a web application that is accessed by multiple users from different locations worldwide. Let's say I have an "edit" form for a specific document and two (or more) users are editing the document at the same time. I know that both of the users can edit the document and submit it, but user1 will not see that user2 made changes to the document and might submit an older version of it.

I was thinking about adding some kind of a lock, but then, if user1 only opened the document for edit, but never changed anything (and kept it open) user2 will never be able to edit it. Therefore, I was thinking to add a Timeout for the editor, but then user1 might time out before he finished doing his changes to the document (let's say, went out for launch).

The question is, how would one prevent the document from being edited from one user while the other changes it?

Note: if this question does not belong here, please explain why and where could I ask such a question.

Best Answer

The basics of implementing optimistic concurrency aren't that hard.

First, you'll need a way to identify a row (or series of rows) in your database (think version number).

Second, when your application loads the data for your user's to review or edit, load the version of the data as well (see above).

Third, when your user goes to save their changes, you'll want to ensure that the version of the data they're changing matches the version of data that exists in the database. If the version numbers don't match then you'll raise and handle some kind of stale data exception.

Related Topic