• Thread-safety with regular expressions in Java


    As mentioned in our introduction to the Pattern and Matcher classes, the Java regular expression API has been designed to allow a single compiled pattern to be shared across multiple match operations. Our examples focussed on creating multiple Matchers in the same thread. But in fact:

    You can safely call Pattern.matcher() on the same pattern from different threads and safely use the matchers concurrently.

    In other words, the Pattern is a "fixed representation" of the regular expression. All of the logic around performing a match— and hence, any state that changes during a match operation— is held in the Matcher object.

    It is also safe to construct matchers without synchronization (using the call to Pattern.matcher()). 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 object1.

    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. But it's not clear why you'd want to do that...


    1. If you're not sure what is meant by correctly see, then see the section of this site on synchronization of variables with main memory.

    From: http://www.javamex.com/tutorials/regular_expressions/thread_safety.shtml#.UxCAJc4rk3Y

    http://stackoverflow.com/questions/9756453/multithreading-java-regex

     

  • 相关阅读:
    ACwing 199 约数之和
    Acwing 222 青蛙的约会
    Acwing 220 最大公约数
    Acwing 200 Hankson的趣味题
    牛客 同余方程
    Acwing 198 反素数
    2020牛客多校 第六场B
    牛客 计数器
    Java基础-快捷键以及DOS命令
    A1111 Online Map (30分)(最短路径、Dijkstra+DFS)
  • 原文地址:https://www.cnblogs.com/diyunpeng/p/3574289.html
Copyright © 2020-2023  润新知