Jeriho
Jeriho

Reputation: 7299

Is this function safe for concurrent execution?

  def isSafe( i:Int) = {
    var count = i
    var acc = 0
    while(count!=0){
      acc += i*i
      count -= 1
    }
    acc
  }

Upvotes: 1

Views: 146

Answers (2)

axel22
axel22

Reputation: 32335

If by safe you mean that it returns the same result independently of how many threads invoke it and in which order, then yes, it's safe. This is because it doesn't modify any shared memory locations, only its local variables.

Upvotes: 7

Kevin Wright
Kevin Wright

Reputation: 49705

It's safe, there's no shared state that could lead to cross-thread contamination.

It's also massively over-complicated, the following definition is both shorter and faster:

def isSafe(i: Int) = i * i * i

Upvotes: 3

Related Questions