【发布时间】:2021-04-01 23:23:58
【问题描述】:
case class Item(id: String, count: Int).
class ItemRepo(db: Database) {
val query = TableQuery[ItemTable]
def updateAmount(id: String, incCount :Int) = {
val currentRow = db.run(query.filter(_.id === id).result).head
val updatedRow = Item(currentRow.id, currentRow.count + incCount)
db.run((query returning query).insertOrUpdate(updatedRow))
}
上面的代码有一个竞争条件 - 如果两个线程并行运行,它们可能都读取相同的计数,并且只有最后一个更新线程会增加它们的 incCount。
我怎样才能避免这种情况?我尝试在执行query.filter 的行中使用.forUpdate,但它不会阻塞另一个线程。我错过了什么吗?
【问题讨论】:
-
不要破坏您的帖子。通过在本网站上发布,您已不可撤销地授予 Stack Exchange 网络以CC BY-SA 4.0 license 分发该内容的权利,只要它认为合适即可。有关删除的替代方法,请参阅:I've thought better of my question; can I delete it?
标签: postgresql scala slick