Template Engine Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Engine runs in O(n) time and O(n) space, in Java as in every other language.
- ✓The JDK ships no HTML template engine and no HTML encoder. It does ship every part needed to build one: `java.util.regex.Pattern` and `Matcher` for the lexer, `java.lang.StringBuilder` for the sink, a `@FunctionalInterface` plus lambdas for the compiled steps, `java.util.List.copyOf` for an immutable plan, and `java.util.concurrent.ConcurrentHashMap.computeIfAbsent` for the cache.
- ✓Make the compiled plan immutable and publish it through a `final` field, so the Java Memory Model's final-field freeze guarantees no other thread can observe a half-built step list.
- ✓The Java trap: `computeIfAbsent` locks the target bin of a `ConcurrentHashMap` for the whole duration of your mapping function.
- ✓A plan built from lambdas gives the call site inside the render loop several distinct implementation classes.
What Template Engine actually is
Template Engine in Java: what you actually reach for
Java implementation
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.*;
public final class Board {
public record Safe(String html) {} // the only raw opt-out
@FunctionalInterface interface Step { void emit(Map<String, Object> c, StringBuilder o); }
private static final Pattern HOLE = Pattern.compile("\\{\\{\\s*(\\w+)\\s*}}");
private static final ConcurrentHashMap<String, List<Step>> PLANS = new ConcurrentHashMap<>();
private static void write(Object v, StringBuilder o) {
if (v instanceof Safe s) { o.append(s.html()); return; }
String t = String.valueOf(v);
for (int i = 0; i < t.length(); i++) { // charAt beats a regex replace chain
switch (t.charAt(i)) {
case '&' -> o.append("&");
case '<' -> o.append("<");
case '>' -> o.append(">");
case '"' -> o.append(""");
default -> o.append(t.charAt(i));
}
}
}
static List<Step> compile(String src) { // runs once per distinct source
List<Step> steps = new ArrayList<>();
Matcher m = HOLE.matcher(src);
int pos = 0;
while (m.find()) {
if (m.start() > pos) {
String lit = src.substring(pos, m.start()); // copies, since JDK 7u6
steps.add((c, o) -> o.append(lit));
}
String key = m.group(1);
steps.add((c, o) -> write(c.get(key), o));
pos = m.end();
}
String tail = src.substring(pos);
if (!tail.isEmpty()) steps.add((c, o) -> o.append(tail));
return List.copyOf(steps); // immutable, safely published
}
public static String render(String src, Map<String, Object> ctx) {
StringBuilder o = new StringBuilder(src.length() + 64); // beat the 16-char default
for (Step s : PLANS.computeIfAbsent(src, Board::compile)) s.emit(ctx, o);
return o.toString();
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Template Engine?
The JDK ships no HTML template engine and no HTML encoder. It does ship every part needed to build one: `java.util.regex.Pattern` and `Matcher` for the lexer, `java.lang.StringBuilder` for the sink, a `@FunctionalInterface` plus lambdas for the compiled steps, `java.util.List.copyOf` for an immutable plan, and `java.util.concurrent.ConcurrentHashMap.computeIfAbsent` for the cache. `String.format` and `java.text.MessageFormat` exist but handle locales and numbers, not markup, and neither encodes anything. The ecosystem answers are Freemarker, Thymeleaf and Pebble; each parses once into a reusable object and caches it by name.
What is the most common Java mistake when implementing Template Engine?
`computeIfAbsent` locks the target bin of a `ConcurrentHashMap` for the whole duration of your mapping function. If compiling a template pulls in a partial and recursively calls `computeIfAbsent` on the same map, the outcome depends on where the two keys hash. Different bins and it silently succeeds; the same bin and the map detects the re-entrancy and throws `IllegalStateException: Recursive update`. Reproducibility is therefore a function of your template names, so it passes CI and fires in production the day someone adds a partial whose name collides. Resolve includes before entering the lambda.
How does Template Engine actually perform in Java?
A plan built from lambdas gives the call site inside the render loop several distinct implementation classes. HotSpot's inline cache copes with one or two receivers, then goes megamorphic and stops inlining `emit` entirely, so a plan with many step shapes renders measurably slower than one with two. Keeping exactly two kinds, literal and hole, is worth more than any micro-optimisation inside them. `String.substring` has copied rather than shared backing arrays since JDK 7u6, so literal chunks are real allocations, taken once at compile time where you want them. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.