什么是在Java Spring应用程序中解决竞态条件的最佳方法?

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年5月4日 17:19:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/61588873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定