2015-08-28 37 views
0

在Windows 7 我在斯卡拉/播放框架新手玩2.4,我有如下一個動作:奇怪的行爲

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 
} 

我希望執行順序應該是1 ,2,4,3。然而,輸出是1,2,3,4並且全部在相同的線程中。然後我改變的代碼,與

val result = delayed.map{ message => 
    println(new Date() + "-3-" + Thread.currentThread().getId) 
    Ok(message) 
} 

取代

val result = delayed.map{ 
    println(new Date() + "-3-" + Thread.currentThread().getId) 
    Ok(_) 
} 

然後輸出爲1,2,4,3,和圖3是在不同的線程。

有人能告訴我原因嗎?謝謝!

回答

1

讓我們稍微重構代碼。第一個:

// 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 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)