How to use scala actors

2019-08-19 04:22发布

问题:

How to solve this using scala Actors: I have a program that finds out the frequencies of identifiers in files under a given path. The encoding assumed is UTF-8. I want to solve the same problem with scala actors.

//program to find frequencies of identifiers
import java.io._
import java.util.concurrent._
import java.util.concurrent.atomic._

object Main {
  // visit all files in dir
  def processDirectory(dir: File, visit: (File) => Unit) {
    for (f <- dir.listFiles) 
      if (f.isDirectory) processDirectory(f, visit)
      else visit(f)
  }

  //counters for all identifiers
  val frequencies = new scala.collection.mutable.HashMap[String, Int]

  // Finds all identifiers in a file and increments their counters
  def process(f: File) {
    val contents = scala.io.Source.fromFile(f, "UTF-8").mkString
    val pattern = "[a-zA-Z_][0-9a-zA-Z_]*".r
    for (m <- pattern.findAllIn(contents))
      frequencies(m) = frequencies.getOrElse(m, 0) + 1
  }

  def main(args: Array[String]) {   //Give path of a directory here
    processDirectory(new File(args(0)), process _)

    println("Ten most common identifiers:")
    val sorted = frequencies.values.toBuffer.sortWith(_ > _)
    for (i <- 0 until 10)      
      for ((k, v) <- frequencies) 
        if (v == sorted(i)) println(k + " " + v)
  }
}

Also please explain the concept of scala actors. I am confused about scala actors.

回答1:

Actors help with concurrent design. There's nothing concurrent about this. People who want parallelism, for performance, sometimes want to do exactly what you're doing: take some simple filesystem-munging thing, throw extra threads at it, and see if it's faster. However, this is a disk, and random access is extremely expensive, so you've nothing to gain from parallel processing, Actor-abusing or otherwise.

Scala's Actors come from Erlang. So please see if Concurrency Oriented Programming in Erlang (pdf), by one of Erlang's designers, helps you get an idea of what they're about. They're not really about throwing threads at tasks to make those tasks go faster.

Some resources to help with Scala's Actors:

  • Actors in Scala -- it's published at the end of the month, but PrePrint PDFs are available now.

  • Scala Actors: A Short Tutorial