title: Modify collection inside a Spark RDD foreach
body: <p>I'm trying to add elements to a map while iterating the elements of an RDD. I'm not getting any errors, but the modifications are not happening. </p>
  
  <p>It all works fine adding directly or iterating other collections:</p>
  
  <pre><code>scala&gt; val myMap = new collection.mutable.HashMap[String,String]
  myMap: scala.collection.mutable.HashMap[String,String] = Map()
  
  scala&gt; myMap("test1")="test1"
  
  scala&gt; myMap
  res44: scala.collection.mutable.HashMap[String,String] = Map(test1 -&gt; test1)
  
  scala&gt; List("test2", "test3").foreach(w =&gt; myMap(w) = w)
  
  scala&gt; myMap
  res46: scala.collection.mutable.HashMap[String,String] = Map(test2 -&gt; test2, test1 -&gt; test1, test3 -&gt; test3)
  </code></pre>
  
  <p>But when I try to do the same from an RDD:</p>
  
  <pre><code>scala&gt; val fromFile = sc.textFile("tests.txt")
  ...
  scala&gt; fromFile.take(3)
  ...
  res48: Array[String] = Array(test4, test5, test6)
  
  scala&gt; fromFile.foreach(w =&gt; myMap(w) = w)
  scala&gt; myMap
  res50: scala.collection.mutable.HashMap[String,String] = Map(test2 -&gt; test2, test1 -&gt; test1, test3 -&gt; test3)
  </code></pre>
  
  <p>I've tried printing the contents of the map as it was before the foreach to make sure the variable is the same, and it prints correctly:</p>
  
  <pre><code>fromFile.foreach(w =&gt; println(myMap("test1")))
  ...
  test1
  test1
  test1
  ...
  </code></pre>
  
  <p>I've also printed the modified element of the map inside the foreach code and it prints as modified, but when the operation is completed, the map seems unmodified.</p>
  
  <pre><code>scala&gt; fromFile.foreach({w =&gt; myMap(w) = w; println(myMap(w))})
  ...
  test4
  test5
  test6
  ...
  scala&gt; myMap
  res55: scala.collection.mutable.HashMap[String,String] = Map(test2 -&gt; test2, test1 -&gt; test1, test3 -&gt; test3)
  </code></pre>
  
  <p>Converting the RDD to an array (collect) also works fine:</p>
  
  <pre><code>fromFile.collect.foreach(w =&gt; myMap(w) = w)
  scala&gt; myMap
  res89: scala.collection.mutable.HashMap[String,String] = Map(test2 -&gt; test2, test5 -&gt; test5, test1 -&gt; test1, test4 -&gt; test4, test6 -&gt; test6, test3 -&gt; test3)
  </code></pre>
  
  <p>Is this a context problem? Am I accessing a copy of the data that is being modified somewhere else?</p>