使用双重检查,避免并发下同一个正则表达式编译多次。

feature/net-util
ZhouXY108 2023-05-13 12:57:22 +08:00
parent 4676755967
commit e0d793ba14
1 changed files with 9 additions and 5 deletions

View File

@ -29,13 +29,17 @@ public class RegexUtil {
public static Pattern getPattern(final String regex) { public static Pattern getPattern(final String regex) {
Objects.requireNonNull(regex); Objects.requireNonNull(regex);
if (PATTERN_CACHE.containsKey(regex)) { if (!PATTERN_CACHE.containsKey(regex)) {
return PATTERN_CACHE.get(regex); synchronized (RegexUtil.class) {
} if (!PATTERN_CACHE.containsKey(regex)) {
Pattern pattern = Pattern.compile(regex); Pattern pattern = Pattern.compile(regex);
PATTERN_CACHE.put(regex, pattern); PATTERN_CACHE.put(regex, pattern);
return pattern; return pattern;
} }
}
}
return PATTERN_CACHE.get(regex);
}
public static boolean matches(@Nullable CharSequence input, String regex) { public static boolean matches(@Nullable CharSequence input, String regex) {
return matches(input, getPattern(regex)); return matches(input, getPattern(regex));