优化代码。

feature/net-util
ZhouXY108 2023-06-27 00:24:22 +08:00
parent fc667e5c72
commit 3439e6450d
1 changed files with 12 additions and 13 deletions

View File

@ -16,7 +16,8 @@
package xyz.zhouxy.plusone.commons.util; package xyz.zhouxy.plusone.commons.util;
import java.util.concurrent.ConcurrentHashMap; import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -24,6 +25,8 @@ import javax.annotation.Nullable;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import xyz.zhouxy.plusone.commons.collection.SafeConcurrentHashMap;
/** /**
* {@link Pattern} 256 * {@link Pattern} 256
* *
@ -34,7 +37,7 @@ public final class RegexUtil {
private static final int DEFAULT_CACHE_INITIAL_CAPACITY = 64; private static final int DEFAULT_CACHE_INITIAL_CAPACITY = 64;
private static final int MAX_CACHE_SIZE = 256; private static final int MAX_CACHE_SIZE = 256;
private static final ConcurrentHashMap<String, Pattern> PATTERN_CACHE = new ConcurrentHashMap<>( private static final Map<String, Pattern> PATTERN_CACHE = new SafeConcurrentHashMap<>(
DEFAULT_CACHE_INITIAL_CAPACITY); DEFAULT_CACHE_INITIAL_CAPACITY);
/** /**
@ -77,15 +80,13 @@ public final class RegexUtil {
* *
* @param patterns * @param patterns
* @param cachePattern {@link Pattern} * @param cachePattern {@link Pattern}
* @return Pattern * @return {@link Pattern}
*/ */
public static Pattern[] getPatterns(final String[] patterns, final boolean cachePattern) { public static Pattern[] getPatterns(final String[] patterns, final boolean cachePattern) {
Preconditions.checkNotNull(patterns, "The patterns can not be null."); Preconditions.checkNotNull(patterns, "The patterns can not be null.");
final Pattern[] result = new Pattern[patterns.length]; return Arrays.stream(patterns)
for (int i = 0; i < patterns.length; i++) { .map(pattern -> getPattern(pattern, cachePattern))
result[i] = getPattern(patterns[i], cachePattern); .toArray(Pattern[]::new);
}
return result;
} }
/** /**
@ -96,11 +97,9 @@ public final class RegexUtil {
*/ */
public static Pattern[] getPatterns(final String[] patterns) { public static Pattern[] getPatterns(final String[] patterns) {
Preconditions.checkNotNull(patterns, "The patterns can not be null."); Preconditions.checkNotNull(patterns, "The patterns can not be null.");
final Pattern[] result = new Pattern[patterns.length]; return Arrays.stream(patterns)
for (int i = 0; i < patterns.length; i++) { .map(RegexUtil::getPattern)
result[i] = getPattern(patterns[i]); .toArray(Pattern[]::new);
}
return result;
} }
/** /**