Reputation: 1513
Play 2.4 on Windows 7. I am newbie in Scala/Play framework, I have a action as below:
def delay = Action.async { request =>
println(new Date() + "-1-" + Thread.currentThread().getId)
val delayed = play.api.libs.concurrent.Promise.timeout("Delayed", 10.seconds)
println(new Date() + "-2-" + Thread.currentThread().getId)
val result = delayed.map{
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(_)
}
println(new Date() + "-4-" + Thread.currentThread().getId)
result
}
I expect the execute order should be 1,2,4,3. However the output is 1,2,3,4 and all in same thread. Then I change the code, replace
val result = delayed.map{
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(_)
}
with
val result = delayed.map{ message =>
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(message)
}
Then the output is 1,2,4,3, and 3 is in different thread.
Could somebody tell me the reason? Thanks!
Upvotes: 0
Views: 48
Reputation: 2824
Let's refactor the code a little bit. The first one:
// The code between the braces here is just a code block. It is
// executed immediately to calculate the value of mappingFunction.
// That is before the assignment to mappingFunction.
val mappingFunction = {
println(new Date() + "-3-" + Thread.currentThread().getId)
{ message: String => Ok(message) }
}
val result = delayed.map(mappingFunction)
The second one:
// The code between the braces here is the function that will
// be executed when the future is completed. In which thread it
// will be executed depends on the execution context, and is not
// guaranteed to be the one where mappingFunction is defined.
val mappingFunction = { message: String =>
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(message)
}
val result = delayed.map(mappingFunction)
Upvotes: 1