Scrivio Interview library
InternalsIntermediate6 min read · updated 12 November 2026

Describe lock elision and lock coarsening done by the HotSpot JIT, and give an example of code where they apply.

Lock elision means the JIT removes locking entirely when escape analysis proves the locked object never escapes the current thread; for example, a StringBuffer created and used only inside one method may have all its synchronization removed. Lock coarsening means the JIT merges adjacent synchronized regions on the same object into one, so several sb.append calls in a row on a shared StringBuffer may run under a single lock acquisition instead of one per call. Both are optimisations, not guarantees: whether they happen depends on the JIT, inlining and the JDK version, so correctness must never depend on them.

Why this question is asked

These two optimisations explain why code full of synchronized methods, like old code using StringBuffer, often runs much faster than a naive count of lock operations predicts. They also explain some confusing benchmark results. Interviewers ask about them to see whether we understand what the JIT can prove about our code and where its freedom ends. In this answer, we will recap escape analysis, look at lock elision with an example, look at lock coarsening with an example, see how to observe them, and be clear about why we never rely on them.

1A Quick Recap of Escape Analysis

HotSpot's C2 compiler, the optimising JIT that compiles hot methods, performs escape analysis: it works out whether an object created in a method can ever be seen outside that method's thread. An object escapes if it is stored in a field or a static, passed to a method the compiler cannot see into, returned, or handed to another thread. If none of that happens, after inlining the methods involved, the object is thread-local, and the compiler can treat it specially.

For such objects C2 can allocate them in registers instead of the heap (scalar replacement), and, for this question, remove their locks, because no other thread could ever contend for them.

2Lock Elision: Removing Locks Nobody Can Contend For

StringBuffer is the classic example, because every one of its methods is synchronized. Consider a method that builds a string from local data with a StringBuffer that never leaves the method.

Java
String describe(Order o) {
StringBuffer sb = new StringBuffer(); // local; never stored or passed on
sb.append("Order ").append(o.id()); // synchronized append, twice
sb.append(" for ").append(o.customer()); // and twice more
return sb.toString(); // only the String escapes, not sb
}
// after C2 inlines append() and proves sb does not escape:
// all 4 monitor enter/exit pairs are removed (lock elision)

Notice what makes this possible: sb is created inside the method, every method called on it is inlined, and the only thing returned is the String, a different object. No other thread can ever obtain a reference to sb, so its monitor can never be contended, and the JIT drops the lock operations. The code then runs like StringBuilder. If sb were stored in a field or passed to a method that was too large to inline, escape analysis would have to assume it escapes and keep the locks.

3Lock Coarsening: Merging Adjacent Locks

Coarsening applies even when the object does escape. If the compiled code takes and releases the same lock several times in a row with little in between, C2 can merge those regions into one: lock once, do all the work, unlock once.

Java
// sb is a shared field, so it escapes and elision is impossible
void logLine(String a, String b, String c) {
sb.append(a); // lock sb ... unlock sb
sb.append(", "); // lock sb ... unlock sb
sb.append(b); // lock sb ... unlock sb
sb.append(c); // lock sb ... unlock sb
}
// after coarsening: lock sb once, four appends, unlock sb once
Elision and coarsening side by side
Lock elisionLock coarsening
Needsobject proven not to escapeadjacent locks on the same object
Effectlock operations removedseveral regions merged into one
Examplelocal StringBuffer in a methodconsecutive appends on a shared buffer
Depends onescape analysis and inliningJIT heuristics, code shape

This is legal because the Java Memory Model allows the JVM to make a synchronized region larger, as long as it does not move code out of one. Another thread could already have observed exactly this behaviour, the four appends running together, by chance, so merging them cannot produce a result the program could not have produced anyway. HotSpot limits how far it coarsens, for example it avoids merging across long loops, so that other threads are not locked out for too long.

4Seeing It Happen

We can observe these optimisations with a microbenchmark. A JMH benchmark that builds a string with a local StringBuffer usually runs about as fast as one using StringBuilder once C2 has compiled it, because the locks are gone. Running the same benchmark with escape analysis turned off, -XX:-DoEscapeAnalysis, or with lock elimination turned off, -XX:-EliminateLocks, makes the StringBuffer version noticeably slower. These flags are for experiments, not production, and their exact behaviour can vary by JDK, so check your version.

This is also why naive benchmarks mislead. A loop that only measures a local StringBuffer may report that synchronized is free, because the JIT removed it; the same class used as a shared field tells a different story.

5Why We Never Rely on Them

Both optimisations are things the JIT may do, not things it must do. Elision needs C2 to compile the method, inline every call involved and prove non-escape; a small change, such as a method growing past the inlining limit or a reference passed to a logger, quietly turns it off. Code that runs in the interpreter or in the C1 compiler gets neither optimisation. Different JDK versions and different JVMs have different heuristics.

So correctness must come from the program itself. Removing a lock that is truly needed would be a bug the JIT is careful never to introduce, so these optimisations never make incorrect code correct or correct code incorrect; they only change speed. For performance, the reliable choice is still to use StringBuilder for local string building and unsynchronized collections for thread-confined data, rather than hoping the JIT removes locks we did not need.

6Follow-up questions

Is lock coarsening ever harmful?

It can increase how long a lock is held, which can delay other threads waiting for it. That is why HotSpot avoids coarsening across loops with many iterations and keeps merged regions bounded. In normal code the effect is beneficial or negligible.

Does escape analysis remove the allocation too?

Often, yes. When an object does not escape, C2 can replace it with its fields held in registers or on the stack, so no heap allocation happens at all. Whether that happens depends on the object's size and how it is used, so it is also an optimisation and not a guarantee.

Do these optimisations work for ReentrantLock?

Not in the same way. Lock elision and coarsening target monitorenter and monitorexit, the bytecode of synchronized. ReentrantLock is ordinary Java code built on atomic operations, so the JIT treats it as normal method calls and atomics, which it does not elide on the same rules.

7Conclusion

In this answer, we saw that lock elision removes locking on objects that escape analysis proves never leave the current thread, such as a local StringBuffer, and that lock coarsening merges adjacent synchronized regions on the same object, such as consecutive appends on a shared StringBuffer. Both depend on the C2 compiler, inlining and JDK heuristics, can be seen in benchmarks with flags such as -XX:-EliminateLocks, and are optimisations rather than guarantees, so correctness and even performance planning must not depend on them.

What to say in the interviewAbout 80 seconds aloud

Open with

Both are optimisations the C2 JIT does to synchronized code. Lock elision uses escape analysis: if the compiler can prove an object never escapes the current thread, nobody else can ever lock it, so it removes the lock operations completely.

Then, if they want more

The classic example is a StringBuffer created inside a method, appended to and turned into a String, where only the String leaves the method. After inlining append, the compiler sees sb does not escape and drops all the monitor enter and exit pairs, so it runs like StringBuilder.

Lock coarsening applies even when the object is shared: if the code locks and unlocks the same object several times in a row, like several sb.append calls on a StringBuffer field, the JIT can merge them into one lock acquisition around all the appends.

That is allowed because the memory model lets the JVM make synchronized regions larger, and HotSpot avoids doing it across long loops. You can see the effect in a JMH benchmark by turning off EliminateLocks or DoEscapeAnalysis. But these are optimisations, not guarantees.

They depend on inlining, on C2 compiling the method and on the JDK version, so correctness never depends on them. For local string building I would just use StringBuilder.

About this answer

Last updated
12 November 2026
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 "Describe lock elision and lock coarsening done by the HotSpot JIT, and give an example...": https://scrivio-interview-library.netlify.app/java/synchronization/e270dfb639/