Search code examples
scalaapache-sparkstack-overflowtail-recursion

Catching exception in Spark slows the execution


There is an RDD with elements like this:

( (n_1, n_2, r), List( (t1,t2), (t3,t4), ... )

I'm trying to do the following:

def p_rec_l(k: Int, acc: Double, pvals_sum: Double, n_1: Int, n_2: Int, r: Int): Double = {
  if (k==r-1) return 1 - (pvals_sum + acc)
  return p_rec_l(k+1, acc*f(k.toDouble, n_1, n_2), pvals_sum+acc, n_1, n_2, r)
}

def f(k:Double, n_1: Int, n_2:Int): Double = (n_1-k)*(n_2-k)/((k+1)*(N-n_1-n_2+k+1))
N = 2000000
someRDD.map({
    case (key, value) => (key, {
      val n_1 = key._1; val n_2 = key._2; val r = key._3
      val p_k0 = (0 to n_2-1).iterator.map(j => 1- n_1/(N-j.toDouble)).reduceLeft(_*_)
      val pval = p_rec_l(0, p_k0, 0, n_1, n_2, r)
      value.map({
        case (t1, t2) => (t1, t2, n_1, n_2, r, pval)          
      }) 
    })
})

But if r is quite big there is a stack overflow exception and the full process crashes. I edited the code like this:

someRDD.map({
    case (key, value) => (key, {
      val n_1 = key._1; val n_2 = key._2; val r = key._3
      val p_k0 = (0 to n_2-1).iterator.map(j => 1- n_1/(N-j.toDouble)).reduceLeft(_*_)
      var pval = -1.0
      try{
        pval = p_rec_l(0, p_k0, 0, n_1, n_2, r)
      } catch{
        case e: java.lang.StackOverflowError => pval = -1
      }
      value.map({
        case (t1, t2) => (t1, t2, n_1, n_2, r, pval)          
      }) 
    })
})

Before the edition the program finished in about 7 hours, but now it's been working for 36 hours and hasn't finished yet. Is it possible, that this try-catch clause slows the execution so much? If it is, is there any way to impove it?


Solution

  • Probably better solution would be not to catch StackOverflowError, but instead mark your function with @tailrec annotation (as I see it is tail recursive), so you should avoid StackOverflowError at all

    @tailrec def p_rec_l(k: Int, acc: Double, pvals_sum: Double, n_1: Int, n_2: Int, r: Int): Double = {
      if (k==r-1) 1 - (pvals_sum + acc)
      else p_rec_l(k+1, acc*f(k.toDouble, n_1, n_2), pvals_sum+acc, n_1, n_2, r)
    }
    

    Also, to understand your question a bit better, am I understand right that you compare execution time of successful execution without StackOverflowError and without try-catch, and another execution with try-catch, but with same data which does not cause StackOverflowError, so catch itself is not working while you compare time?