Why does the following code create a deadlock:
object Test extends Application
{
def printProgress(i:Int) =
{
println("Processed " + i)
}
println("A")
(1 to 1000).par.foreach{ i =>
printProgress(i)
}
println("B")
}
(i.e. A
is printed, but neither B
nor any of the Processed ...
lines are printed.)
However the following code does not cause a deadlock:
object Test extends Application
{
println("A")
(1 to 1000).par.foreach{ i =>
println("Processed " + i)
}
println("B")
}
(i.e. everything gets printed.)
I'm running Scala version 2.9.1.final.
Probably because you extend Application, while I could not tell what makes a difference between your two examples.
With Application, the code is executed outside of method main
, in the class initialization. The JVM is severely limited at this point, notably related to multithreading. Application is deprecated in favor of App, which has some magic (trait DelayedInit) which causes the code to be executed in main
. So object Test extends App
should fix it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With