是否节省:
private static final String LUCENE_ESCAPE_CHARS = "[\\\\+\\-\\!\\(\\)\\:\\^\\]\\{\\}\\~\\*\\?]";
private static final Pattern LUCENE_PATTERN = Pattern.compile(LUCENE_ESCAPE_CHARS);
private static final String REPLACEMENT_STRING = "\\\\$0";
并在多线程环境中使用下面的代码,例如 servlet 的 doGet()
?
String escaped = LUCENE_PATTERN.matcher(query).replaceAll(REPLACEMENT_STRING);
我现在主要担心的是增加额外的延迟(例如由于锁定)或出现错误的情况。
最佳答案
是它是安全的。Pattern
对象是线程安全的和Matcher
对象不是。您可以与多个线程共享模式实例。
但不要在线程之间共享 Matcher
实例。
为 Pattern 引用 JavaDoc
Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the
Matcher
class are not safe for such use.
关于java - 在 servlet 的 doGet() 中安全地使用静态编译模式 - matcher.replaceAll(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18954532/