title: Filtering Scala's Parallel Collections with early abort when desired number of results found
body: <p>Given a very large instance of <strong>collection.parallel.mutable.ParHashMap</strong> (or any other parallel collection), how can one abort a filtering parallel scan once a given, say 50, number of matches has been found ? </p>
  
  <p>Attempting to accumulate intermediate matches in a thread-safe "external" data structure or keeping an external AtomicInteger with result count seems to be 2 to 3 times slower on 4 cores than using a regular <strong>collection.mutable.HashMap</strong> and pegging a single core at 100%.</p>
  
  <p>I am aware that <strong>find</strong> or <strong>exists</strong> on Par* collections do abort "on the inside". Is there a way to generalize this to find more than one result ?</p>
  
  <p>Here's the code which still seems to be 2 to 3 times slower on the ParHashMap with ~ 79,000 entries and also has a problem of stuffing <em>more</em> than <strong>maxResults</strong> results into the results CHM (Which is probably due to thread being preempted after <strong>incrementAndGet</strong> but before <strong>break</strong> which allows other threads to add more elements in). Update: it seems the slow down is due to worker threads contending on the counter.incrementAndGet() which of course defeats the purpose of the whole parallel scan :-(</p>
  
  <pre><code>def find(filter: Node =&gt; Boolean, maxResults: Int): Iterable[Node] =
  {
    val counter = new AtomicInteger(0)
    val results = new ConcurrentHashMap[Key,  Node](maxResults)
  
    import util.control.Breaks._
  
    breakable
    {
      for ((key, node) &lt;- parHashMap if filter(node))
      {
        results.put(key, node)
        val total = counter.incrementAndGet()
        if (total &gt; maxResults) break
      }
    }
  
    results.values.toArray(new Array[Node](results.size))
  }
  </code></pre>