Thread-safety with regular expressions in Java

本文探讨了Java正则表达式的线程安全性,解释了如何在多线程环境中安全地使用Pattern和Matcher类。Pattern类可以被多个线程共享并用于创建独立的Matcher实例,而不会引起线程安全问题。

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

 

 

转载于:https://www.cnblogs.com/diyunpeng/p/3574289.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值