Video in progress
In a service that uses exceptions heavily for validation and control flow, CPU and allocation shot up under load. What do exceptions cost in the JVM, and how do you change the design?
The main cost of an exception is fillInStackTrace: the JVM walks the whole stack and records the frames, and then writing to the log turns the stack trace into a string. On a deep Spring stack that is microseconds and kilobytes. For expected cases (validation, "not found") you use result types, and exceptions are left for truly exceptional situations.
📖 Answer
In a profile this looks like: in the flame graph Throwable.fillInStackTrace and StackTraceElement creation take 20-30%, and in the allocation profile StackTraceElement[] and Strings are at the top. The cause is often code like this:
public Optional<User> find(String email) {
try {
return Optional.of(repo.getByEmail(email)); // NotFoundException if not found
} catch (NotFoundException e) {
log.warn("user not found", e); // a full stack trace to the log every time
return Optional.empty();
}
}
What the cost is made of:
- walking the stack, proportional to depth (Spring + proxies + filters = 150+ frames);
- on
getStackTrace()or when writing to the log, frames turn intoStackTraceElementobjects; - kilobytes of text in the log appender: I/O and more allocation.
The throw/catch itself can be cheap if the JIT sees both in one compilation unit. What is expensive is the stack trace.
Design changes:
- Expected outcomes go in values.
Optional,sealed interface Result permits Ok, NotFound, Invalidand Java 21 pattern matching switch. Validation errors come back as a list. - Exceptions without stack traces. For business exceptions,
super(message, null, false, false), which iswritableStackTrace=false. You don't need the stack trace anyway: the cause is known from the message. - Log policy. Don't write expected cases as
warnwith a stack trace;debugor a metric counter is enough. - One handler at the boundary.
@RestControllerAdviceturns the exception into an HTTP response, with no re-wrapping and re-logging at every layer.
After the change I re-measure the allocation rate and CPU. And one more signal: if the same NPE starts appearing in the log without a stack trace, C2 has applied OmitStackTraceInFastThrow, meaning the exception is very hot, and that is a design problem too.
Sign up to mark studied questions and save your progress.