Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is scalas pattern matching regex thread safe?

Tags:

regex

scala

Similar to Is Java Regex Thread Safe?, I would like to know if this usage of scala regex is really thread safe? Are multiple threads able to call m on the same object M without interfering with each other in the result?

object R {
  val pat = """a(\d)""".r
}

class M {

  def m(s: String): Option[Int] = {
     s match {
       case R.pat(i) => Some(i.toInt)
       case _ => None
     }
  }
}
like image 572
Ido Tamir Avatar asked Oct 31 '11 10:10

Ido Tamir


1 Answers

There are more than one class. It breaks down to:

  • scala.util.matching.Regex depends on java.util.regex.Pattern, so, according to JavaDoc, thread-safe.
  • scala.util.matching.Regex.Match depends on java.util.regex.Match, so, according to JavaDoc, not thread-safe.
  • scala.util.matching.Regex.MatchIterator is mutable, and contains java.util.regex.Match, so not thread-safe.
  • scala.util.matching.Regex.MatchData is technically thread-safe, but it only appears as part of the two classes above, so you won't find thread-safe instances of MatchData.
like image 105
Daniel C. Sobral Avatar answered Oct 01 '22 07:10

Daniel C. Sobral