我有一个使用
此函数用于多个线程。 创建线程时,每个线程都有一个传递给
如果使用正则表达式,是否需要在此函数上放置
是,来自Pattern类的Java API文档
Instances of this (Pattern) class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.
如果您正在查看以性能为中心的代码,请尝试使用reset()方法重置Matcher实例,而不是创建新实例。这将重置Matcher实例的状态,使其可用于下一个正则表达式操作。实际上,正是Matcher实例中维护的状态才使它对于并发访问不安全。
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.
尽管您需要记住线程安全性也必须考虑周围的代码,但是您似乎很幸运。匹配器是使用Pattern的matcher工厂方法创建的,并且缺少公共构造函数,这是一个积极的信号。同样,您可以使用compile static方法创建包含模式。
简而言之,如果您执行类似示例的操作:
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
你应该做得不错。
为了清楚起见,对代码示例进行了后续处理:请注意,此示例强烈暗示由此创建的Matcher在Pattern和测试中是线程局部的。即,您不应将由此创建的Matcher暴露给任何其他线程。
坦白说,这就是任何线程安全问题的风险。现实情况是,如果您努力尝试,任何代码都可能被设置为线程不安全的。幸运的是,有很多很棒的书,教给我们很多破坏代码的方式。如果我们避免这些错误,那么将大大降低我们自己出现线程问题的可能性。
快速浏览
Instances of this class are not safe for use by multiple concurrent
threads.
正如@Bob Cross指出的那样,这只是一个问题,如果您竭尽所能允许在单独的
综上所述,您可以重用(保留静态变量)已编译的Pattern,并告诉它们在需要验证某些字符串的正则表达式模式时为您提供新的Matchers。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Validation helpers
*/
public final class Validators {
private static final String EMAIL_PATTERN ="^[_A-Za-z0-9-]+(\\\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$";
private static Pattern email_pattern;
static {
email_pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Check if e-mail is valid
*/
public static boolean isValidEmail(String email) {
Matcher matcher = email_pattern.matcher(email);
return matcher.matches();
}
}
有关上面用于验证电子邮件的RegEx模式,请参见http://zoomicon.wordpress.com/2012/06/01/validating-e-mails-using-regular-expressions-in-java/(接近尾声)(万一它不适合那些需要通过电子邮件验证的人,因为它在这里发布)
以上就是短码网小编为大家整理的《Java Regex线程安全吗?》相关内容,希望大家喜欢。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将联系本站反馈,一经查实,立即处理!
《Java Regex线程安全吗?》文档下载仅供参考学习,下载后请在24小时内删除。
转载注明出处:https://www.duanma.net/article/3aaf02c6608.html