11

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
     }
  }
}
Community
  • 1
  • 1
Ido Tamir
  • 3,017
  • 2
  • 19
  • 28

2 Answers2

13

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.
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
7

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.

Wilfred Springer
  • 10,869
  • 4
  • 55
  • 69
  • 1
    Just remember that although the `Pattern` is thread-safe, any `Matcher` instances obtained from the `Pattern` are not and must be treated as such. The OPs code is safe though. – gpampara Oct 31 '11 at 11:54
  • Suppose I create a `Matcher` and then pass it to multiple threads. Is it threadsafe for each thread to make its own `clone()` of the Matcher and only use the clone? – Dan Burton Oct 31 '11 at 21:49