• 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

     

  • 相关阅读:
    SVN中的Trunk、Tag、Brance的用法
    开发下载地址汇集
    Hessian原理分析
    Java中间件:淘宝网系统高性能利器
    linux进阶
    常见的Hadoop十大应用误解
    搜索引擎汇总
    bat薪酬
    常用的快速Web原型图设计工具
    apache kafka消息服务
  • 原文地址:https://www.cnblogs.com/diyunpeng/p/3574289.html
Copyright © 2020-2023  润新知