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

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,12 +29,16 @@ public class RegexUtil {
public static Pattern getPattern(final String regex) {
Objects.requireNonNull(regex);
if (PATTERN_CACHE.containsKey(regex)) {
return PATTERN_CACHE.get(regex);
if (!PATTERN_CACHE.containsKey(regex)) {
synchronized (RegexUtil.class) {
if (!PATTERN_CACHE.containsKey(regex)) {
Pattern pattern = Pattern.compile(regex);
PATTERN_CACHE.put(regex, pattern);
return pattern;
}
}
}
Pattern pattern = Pattern.compile(regex);
PATTERN_CACHE.put(regex, pattern);
return pattern;
return PATTERN_CACHE.get(regex);
}
public static boolean matches(@Nullable CharSequence input, String regex) {