问题描述
阅读Play-Slick DBAction 代码,我认为此代码可能包含竞争条件:
Reading Play-Slick DBAction code, I thought that this code might contain a race condition:
object DBAction{
// snip
def apply(r: (RequestWithDbSession) => Result)(implicit app:Application) = {
Action { implicit request =>
AsyncResult {
DB.withSession{ s:scala.slick.session.Session =>
Future(r( RequestWithDbSession(request,s) ))(executionContext)
}
}
}
}
函数 r
在未来时间运行,在 withSession
返回一个 Future[Result] 之后,并调用 session.close()
.这段代码中是否存在竞争条件?
The function r
runs at a future time, after withSession
has returned a Future[Result], and called session.close()
. Is there a race condition in this code?
推荐答案
我不确定这是否称为竞争条件.但是在我看来,您认为这里出了点问题是正确的.将来执行代码时,会话可能不再有效.
I am not sure if that is called a race condition. However to me it seems that you are correct that something is wrong here. The session might no longer be valid when the future executes the code.
最好在将来反转执行并请求数据库会话:
It would be better to invert the execution and request a database session from within the future:
Async {
Future {
DB.withSession{ s:scala.slick.session.Session =>
r( RequestWithDbSession(request, s) )
}
}
}
这篇关于玩流畅和异步 - 这是竞争条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!