Java Regex线程安全吗? [英] Is Java Regex Thread Safe?

查看:146
本文介绍了Java Regex线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Pattern#compile Matcher 的函数来搜索模式的字符串列表。

I have a function that uses Pattern#compile and a Matcher to search a list of strings for a pattern.

此函数用于多个线程。创建线程时,每个线程都将传递给 Pattern#compile 的唯一模式。线程和模式的数量是动态的,这意味着我可以在配置期间添加更多 Pattern 和线程。

This function is used in multiple threads. Each thread will have a unique pattern passed to the Pattern#compile when the thread is created. The number of threads and patterns are dynamic, meaning that I can add more Patterns and threads during configuration.

如果它使用正则表达式,我是否需要在此函数上放置 synchronize ? java线程中的正则表达式是否安全?

Do I need to put a synchronize on this function if it uses regex? Is regex in java thread safe?

推荐答案

,来自模式类


此(Pattern)类的实例是不可变的,并且可供多个并发线程使用。 Matcher类的实例不适合此类使用。
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实例中维护的状态导致它对并发访问不安全。

If you are looking at performance centric code, attempt to reset the Matcher instance using the reset() method, instead of creating new instances. This would reset the state of the Matcher instance, making it usable for the next regex operation. In fact, it is the state maintained in the Matcher instance that is responsible for it to be unsafe for concurrent access.

这篇关于Java Regex线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆