英文:
What's best way to resolve race condition in Java Spring app?
问题
我在Spring上开发了一个简单的测验网页应用程序,它实现了“测验按钮”,在客户端,玩家应该比其他玩家更快地点击按钮以获取积分。所以我有一个控制器方法如下:
@RequestMapping(value = "/pressButton", method = RequestMethod.POST)
public String processButtonClick(Authentication authentication) {
// 返回第一个点击按钮的玩家姓名
}
如何检查哪个用户首先点击了按钮?如何在数据库更新时防止竞态条件?
英文:
I develop simple quiz web application on Spring, that implements "Quiz button", on client side players should click the button faster than other to get points. So I have controller method like
@RequestMapping(value = "/pressButton", method = RequestMethod.POST)
public String processButtonClick(Authentication authentication) {
//return first player name
}
How to check what user clicked that first? How to prevent race condition while db update?
答案1
得分: 0
你可以使用synchronized
为你的方法分配,这样它就不会同时运行多次。
英文:
You could assign your method with synchronized
, then it will not run simultaneously many times.
答案2
得分: 0
我建议在您的数据库中为 userId 和 questionId 的组合添加唯一约束。如果服务实例只有一个,那么同步将起作用,但在高度可扩展的环境中很少出现这种情况。Redis 锁是另一个可行的选择。
英文:
I suggest go with adding unique constraint for userId and questionId combination in your DB. synchronized will work only if there is only once instance of service, which is rarely there for highly scalable environment. Redis lock is another viable option.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论