简体   繁体   中英

How to prevent two users from taking same action on a data record in a web application?

We have a web application backed by spring framework which displays list of records to the users. We have a requirement where-in we want to restrict single record being actioned from two users at the same time. ie if multiple users are trying to action the same record, request for user which action first is processed rest all should not be able to process it.

We have looked at locking technique (optimistic locking) but not sure if this is the correct or only approach for achieving this functionality.

Also, if optimistic locking is the correct approach, any pointers in that direction would be appreciated.

Optimistic Locking is indeed the usual technique to solve this problem, and it does exactly you ask for: If several users want to perform conflicting actions at the same time, only the first such action succeeds, while all others are rejected. Combining this with informing the other users that their request failed because somebody else was faster, and giving them the option to see what the other user did allows them to reconcile their changes, and try again if necessary.

The advantage of Optimistic Locking is that it only springs into action in the event of an actual conflict. This is optimal if conflicts are rare, and that's why this technique is called "optimistic" locking.

The disadvantage of Optimistic Locking is that it discards user work in the event of a conflict. If conflict is frequent, and the work being submitted significant, simply discarding that work may be too wasteful. Also, sometimes the work has side effects beyond updating a database that must occur only once. For instance, the work may involve sending a letter or email, which can not be recalled in case of an optimistic locking failure.

In these cases, you'll want to prevent users from starting conflicting work rather than waiting until they wish to save their work. This is usually accomplished by allowing a user to take ownership of an issue at the application level before starting the actual work. Combined with ensuring that only a single user can take ownership at the same time (through Optimistic Locking), this prevents conflicting work from being started. The disadvantage of this technique is that the user is required to take an additional action even if there turns out to be no conflict, so this optimizes for cases where conflict is expensive or frequent.

As for how to use optimistic locking, there are plenty of good tutorials on the internet. I'd start by checking the reference manuals of Spring and the JPA implementation you use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM