Skip to content

Commit

Permalink
On stub matching, first checking if precompiled Pattern exists in loc…
Browse files Browse the repository at this point in the history
…al cache (#175)
  • Loading branch information
azagniotov authored Mar 3, 2021
1 parent dd01718 commit 26b85e0
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io.github.azagniotov.stubby4j.caching.Cache;

import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
Expand Down Expand Up @@ -133,11 +134,7 @@ boolean match(final String patternCandidate, final String subject, final String

private boolean match(final String patternCandidate, final String subject, final String templateTokenName, final Map<String, String> regexGroups, final int flags) {
try {
final int patternHashCodeRegexFlagKey = patternCandidate.hashCode() + flags;
final Pattern computedPattern = Pattern.compile(patternCandidate, flags);

REGEX_PATTERN_CACHE.putIfAbsent(patternHashCodeRegexFlagKey, computedPattern);

final Pattern computedPattern = getCachedPatternOrCompileNew(patternCandidate, flags);
final Matcher matcher = computedPattern.matcher(subject);
final boolean isMatch = matcher.matches();
if (isMatch) {
Expand All @@ -160,4 +157,16 @@ private boolean match(final String patternCandidate, final String subject, final
return match(patternCandidate, subject, templateTokenName, regexGroups, Pattern.LITERAL);
}
}

private Pattern getCachedPatternOrCompileNew(final String patternCandidate, int flags) {
final int patternHashCodeRegexFlagKey = patternCandidate.hashCode() + flags;
final Optional<Pattern> compiledPatternOptional = REGEX_PATTERN_CACHE.get(patternHashCodeRegexFlagKey);

return compiledPatternOptional.orElseGet(() -> {
final Pattern computedPattern = Pattern.compile(patternCandidate, flags);
REGEX_PATTERN_CACHE.putIfAbsent(patternHashCodeRegexFlagKey, computedPattern);

return computedPattern;
});
}
}

0 comments on commit 26b85e0

Please sign in to comment.