Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

What is wrong with this hot-path code and how do you fix it?

Java
boolean valid(String s) {
return s.matches("[A-Z]{3}-\\d{4}");
}

String.matches compiles the regular expression into a new Pattern on every call, and compiling is far more expensive than matching, so in a hot path most of the time goes into rebuilding the same Pattern. The fix is to compile it once, private static final Pattern P = Pattern.compile("[A-Z]{3}-\\d{4}"), and call P.matcher(s).matches(). This is safe because Pattern is immutable and thread-safe, while a Matcher is not, so we create a fresh one per call. And matches() requires the whole input to match, unlike find(), which searches anywhere.

Why this question is asked

Validation methods like this one run on every request, often several times, so a small inefficiency is multiplied by millions. String.matches looks like a harmless convenience, and it is fine in a test or a startup check, but in a hot path it repeats expensive work for nothing. Interviewers ask this coding question to see whether we know the cost model of Java regex and the thread-safety rules of its two main classes. In this answer, we will see what String.matches does inside, compile the pattern once, explain why that is thread-safe, compare matches, find and lookingAt, and add a note on what \d matches.

1A Quick Recap of Pattern and Matcher

Java's regex API has two main classes. A Pattern is the compiled form of a regular expression: the string is parsed and turned into a tree of node objects that knows how to match. A Matcher is the state of one matching operation of that Pattern against one input: the current position, the groups found so far and so on.

Compiling is the expensive part. It parses the expression, builds the node tree, and allocates many objects. Matching a short input like ABC-1234 against an already-compiled Pattern is cheap by comparison.

2What String.matches Does Inside

String.matches is a convenience method. It hands the regex to Pattern.matches, which compiles a new Pattern, creates a Matcher and calls matches(). Nothing is cached, so every call repeats the compilation.

Java
// What s.matches(regex) does, in effect
public boolean matches(String regex) {
return Pattern.compile(regex).matcher(this).matches(); // compile on every call
}
boolean valid(String s) {
return s.matches("[A-Z]{3}-\\d{4}"); // 1 million calls = 1 million compilations of the same pattern
}
Step throughCost per call
  1. s.matches(regex)per call: parse regex, build Pattern, new Matcher, match
  2. Compiled once into a static Patternonce per class load
  3. P.matcher(s).matches()per call: new Matcher, match only

3 steps in order. Play them, or step through them one at a time.

Moving compilation out of the call removes the most expensive step from the hot path.

So at a million requests the code compiles the same pattern a million times and throws each one away, adding CPU and garbage. In a JMH benchmark the precompiled version is typically many times faster for a short pattern and input like this; the exact ratio depends on the pattern and the JDK, so measure in your own context. String.replaceAll, replaceFirst and split with a multi-character regex have the same behaviour, because they compile the pattern each time too.

3Fix: Compile Once, Match Per Call

We move the compilation into a static final field, so it happens once when the class is initialised, and each call only creates a Matcher and runs it.

Java
private static final Pattern CODE = Pattern.compile("[A-Z]{3}-\\d{4}");
boolean valid(String s) {
return CODE.matcher(s).matches();
}
valid("ABC-1234"); // true
valid("abc-1234"); // false: lowercase letters
valid("ABC-12345"); // false: matches() needs the whole input to match
// Java 11+: a ready-made predicate for the same whole-input match
private static final Predicate<String> IS_CODE = CODE.asMatchPredicate();
IS_CODE.test("ABC-1234"); // true

Notice that the pattern is also validated at class initialisation, so a typo in the regex fails fast when the class loads rather than on the first request. asMatchPredicate() is handy for streams and validation helpers, and it uses matches() semantics too.

4Why the Static Pattern Is Thread-Safe and a Shared Matcher Is Not

Pattern is immutable: once compiled, nothing in it changes, so any number of threads can use the same instance at the same time. That is why storing it in a static final field shared by all request threads is safe.

Matcher is the opposite. It holds mutable state about one match in progress, such as the current position and group boundaries. If two threads shared a Matcher, one thread's reset or match would overwrite the other's state, giving wrong answers. So we never store a Matcher in a field; we create a fresh one with pattern.matcher(input) for each use. Creating a Matcher is cheap, a small object with a few arrays, and short-lived objects like it are what the young generation collects most efficiently.

Java
// Broken: a Matcher shared between threads
private static final Matcher SHARED = CODE.matcher("");
boolean validBroken(String s) {
return SHARED.reset(s).matches(); // two threads at once can corrupt each other's state
}

5Matches, find and lookingAt

The three Matcher methods answer different questions, and choosing the wrong one is a common bug in validation code. matches() asks whether the whole input matches the pattern. find() asks whether the pattern occurs anywhere in the input, and can be called repeatedly to find each occurrence. lookingAt() asks whether the input starts with a match.

Java
CODE.matcher("ABC-1234").matches(); // true
CODE.matcher("ref ABC-1234 ok").matches(); // false: there is text around the code
CODE.matcher("ref ABC-1234 ok").find(); // true: the code appears inside
CODE.matcher("ABC-1234 ok").lookingAt(); // true: the input starts with a code

For validation we want matches(), or find() with a pattern anchored by ^ and $. Using find() without anchors would accept xxABC-1234yy, which is a security-relevant mistake when the regex guards input. A small detail worth knowing: \d matches only the ASCII digits 0 to 9 by default, which is usually what validation wants, while with the UNICODE_CHARACTER_CLASS flag it also matches digits from other scripts, such as Arabic-Indic digits.

6Follow-up questions

Is a regex the best tool for such a simple format?

For a fixed format like three capitals, a dash and four digits, a hand-written check of length and characters is faster still and has no regex at all. It is also more code and harder to change, so I would use a precompiled Pattern unless profiling shows that this check is really a bottleneck.

Does String.split also compile a pattern every time?

Usually yes. It has a fast path that skips regex for a single character that is not a regex metacharacter, or an escaped one, such as split(",") or split("\\."). For anything longer it compiles a Pattern on each call, so in a hot path a static Pattern with its split method is better.

Can a regex in a hot path be dangerous beyond performance?

Yes. Patterns with nested quantifiers, such as (a+)+, can take exponential time on certain inputs, which is called catastrophic backtracking and can be used for denial of service. Keep validation patterns simple, anchored and tested against long malicious inputs, and limit input length before matching.

7Conclusion

In this answer, we saw that String.matches compiles a new Pattern on every call, which in a hot path means repeating the most expensive step millions of times. Compiling once into a static final Pattern and calling matcher(s).matches() per call removes that cost and validates the regex at class load. This is safe because Pattern is immutable and thread-safe, while Matcher holds per-match state and must be created per use. Finally, matches() requires the whole input to match, find() searches anywhere and lookingAt() checks the start, so validation should use matches() or anchors.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is that String.matches compiles the regex every single time it is called. Internally it is Pattern.compile of the regex, then a matcher, then matches. Compiling means parsing the expression and building a tree of node objects, which is far more expensive than matching an eight-character input, so in a hot path most of the CPU goes into rebuilding the same Pattern and throwing it away, plus the garbage that creates.

Then, if they want more

The fix is to compile once: a private static final Pattern field with Pattern.compile of that expression, and the method becomes return P.matcher(s).matches(). As a bonus, a typo in the regex now fails when the class loads, not on the first request.

This is safe to share because Pattern is immutable and thread-safe, so every request thread can use the same instance. Matcher is not thread-safe, because it holds the state of one match, so I create a new one per call, which is cheap, and I never store one in a field.

I would also make sure we use the right method: matches requires the whole input to match, which is what validation wants, while find succeeds if the pattern appears anywhere, so with find this would accept something like xxABC-1234yy unless the pattern is anchored. And on Java 11 or later, asMatchPredicate gives a ready-made predicate for the same check.

About this answer

Last updated
12 November 2026
Versions it names
Java 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is wrong with this hot-path code and how do you fix it?": https://scrivio-interview-library.netlify.app/java/strings/49a2e13335/