A backend engineer's journey of learning and growth.
by kan01234
High CPU usage in a Java application is a common but frustrating issue. It can lead to degraded performance, long response times, and even downtime if left unchecked. The good news is that high CPU typically comes from a small number of repeatable patterns.
In this post, we’ll cover the most common causes of high CPU usage in Java applications and the practical solutions for each.
Before diving into patterns, always start with a systematic approach:
Check which process is consuming CPU
top -H -p <pid>
Shows per-thread CPU usage in the Java process.
printf '%x\n' <tid>
jstack <pid>
output (nid=0x...
).Once you’ve isolated the culprit, it usually falls into one of the categories below.
Pattern:
Code runs in a loop without yielding, often retrying endlessly.
while (!condition) {
// no sleep or backoff
}
Impact:
Thread spins at 100% CPU.
Solution:
Pattern:
Polling sockets, files, or queues in a tight loop.
while ((bytes = socket.read(buf)) != -1) {
// no blocking, no select()
}
Impact:
CPU wasted on busy polling instead of waiting.
Solution:
Pattern:
GC
state consuming CPU.Impact:
CPU dominated by GC threads, application slows.
Solution:
G1GC
, ZGC
, Shenandoah
).jstat
, GC logs, or JFR.Pattern:
Multiple threads fighting for the same lock.
synchronized (shared) {
// heavy work
}
Impact:
CPU spikes as threads spin or block waiting for locks.
Solution:
ConcurrentHashMap
, ReadWriteLock
).Pattern:
O(n^2)
) over large datasets.Impact:
CPU usage grows disproportionately with input size.
Solution:
Pattern:
Heavy logging inside request/response paths.
log.info("Request: {}", payload); // for every request
Impact:
String concatenation, log formatting, and I/O overhead cause CPU burn.
Solution:
Pattern:
Impact:
CPU wasted either in retries or inefficient I/O handling.
Solution:
top
, jstack
, and profilers.High CPU usage in Java applications is almost always traceable to a handful of root causes. By combining monitoring, thread dumps, and profiling, you can isolate the culprit quickly and apply targeted fixes:
With a systematic approach, solving high CPU usage becomes less of a panic and more of a repeatable engineering playbook.
tags: java - performance