zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    php -- 魔术方法 之 对象输出 : __toString()
    php -- each()、list()
    php -- 魔术方法、魔术常量 简单介绍
    webbench
    md5sum/opensll md5
    shopt
    MD5
    print显示特定的数据格式
    gdb调试4--回退
    字符串化#、拼接字符##和可变参数宏(...和_ _VA_ARGS_ _)
  • 原文地址:https://www.cnblogs.com/diyunpeng/p/3574289.html
Copyright © 2011-2022 走看看