Is Java Regex Thread Safe?

后端 未结 5 838
忘掉有多难
忘掉有多难 2020-11-27 03:24

I have a function that uses Pattern#compile and a Matcher to search a list of strings for a pattern.

This function is used in multiple th

5条回答
  •  忘掉有多难
    2020-11-27 03:50

    Thread-safety with regular expressions in Java

    SUMMARY:

    The Java regular expression API has been designed to allow a single compiled pattern to be shared across multiple match operations.

    You can safely call Pattern.matcher() on the same pattern from different threads and safely use the matchers concurrently. Pattern.matcher() is safe to construct matchers without synchronization. Although the method isn't synchronized, internal to the Pattern class, a volatile variable called compiled is always set after constructing a pattern and read at the start of the call to matcher(). This forces any thread referring to the Pattern to correctly "see" the contents of that object.

    On the other hand, you shouldn't share a Matcher between different threads. Or at least, if you ever did, you should use explicit synchronization.

提交回复
热议问题