保存事件时的竞争条件
我有两个不同的端点,例如:
endpoint1 => /api/user
endpoint2 => /api/user/roles
想象一下这两个端点同时调用相同的方法。
public List activeRoles(userId) {
var roles = repository.findAllRolesOfUser(userId);
if (roles == null) {
var role = new Role("DEFAULT", userId);
repository.save(role);
return Arrays.asList(role)
} else {
return roles;
}
}
当我同时从端点 1 和端点 2 调用 activeRoles(userId) 方法时,它会导致竞争条件,并且在数据库中创建两次“DEFAULT”角色。有办法避免吗?
注意:我不能使用唯一约束。
I have two different endpoints like:
endpoint1 => /api/user
endpoint2 => /api/user/roles
Imagine that these two endpoints call same method at the same time.
public List activeRoles(userId) {
var roles = repository.findAllRolesOfUser(userId);
if (roles == null) {
var role = new Role("DEFAULT", userId);
repository.save(role);
return Arrays.asList(role)
} else {
return roles;
}
}
When I call activeRoles(userId) method from endpoint1 and endpoint2 at the same time, it causes race condition and "DEFAULT" role is created twice in the database. Is there a way to avoid it?
Note: I cannot use unique constraint.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在java中使用同步。
Use syncronized in java.