Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala deadlock with parallel collections

Tags:

scala

deadlock

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.

like image 847
dsg Avatar asked Nov 04 '11 06:11

dsg


1 Answers

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.

like image 78
Didier Dupont Avatar answered Nov 04 '22 17:11

Didier Dupont