From 26b85e0a8d8b5d18b4010789d61b6d850379b8a9 Mon Sep 17 00:00:00 2001 From: Alexander Zagniotov Date: Wed, 3 Mar 2021 20:40:12 +0900 Subject: [PATCH] On stub matching, first checking if precompiled Pattern exists in local cache (#175) --- .../stubby4j/stubs/RegexParser.java | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java b/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java index f39555c08..a952de233 100644 --- a/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java +++ b/src/main/java/io/github/azagniotov/stubby4j/stubs/RegexParser.java @@ -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; @@ -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 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) { @@ -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 compiledPatternOptional = REGEX_PATTERN_CACHE.get(patternHashCodeRegexFlagKey); + + return compiledPatternOptional.orElseGet(() -> { + final Pattern computedPattern = Pattern.compile(patternCandidate, flags); + REGEX_PATTERN_CACHE.putIfAbsent(patternHashCodeRegexFlagKey, computedPattern); + + return computedPattern; + }); + } }