Ido Tamir
Ido Tamir

Reputation: 3137

Is scalas pattern matching regex thread safe?

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
     }
  }
}

Upvotes: 11

Views: 1565

Answers (2)

Wilfred Springer
Wilfred Springer

Reputation: 10927

Since Scala's support for regular expressions builds on top of java.util.regex.Pattern, and since instances of that class are threadsafe, I guess the answer is: yes:

It uses java.util.regex.Pattern:

class Regex(regex: String, groupNames: String*) extends Serializable {

  import Regex._

  /** The compiled pattern */
  val pattern = Pattern.compile(regex)

According to the JavaDoc on Pattern, java.util.regex.Pattern is threadsafe:

Instances of this class are immutable and are safe for use by multiple concurrent threads.

Upvotes: 7

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297205

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.

Upvotes: 13

Related Questions