Video in progress
When is the object pool pattern useful on today's JVM, and when is it harmful?
It is useful for external resources that are expensive to create and limited in number: DB connections, threads, large direct buffers. Pooling ordinary Java objects is usually slower and more error-prone with a modern GC.
📖 Answer
You can't imagine a backend without a connection pool: a TCP connection, a TLS handshake, authentication in the database; that is tens of milliseconds on every request. HikariCP reuses connections and limits how many are open at once. That second job matters as much as the first: the pool protects the database.
With ordinary objects the situation is different. In G1 and ZGC, allocating a short-lived object in the young generation is a few instructions (bumping a pointer in the TLAB), and collecting it is nearly free, because only the live objects get copied. A pool, on the other hand:
- keeps the object alive for a long time and moves it to the old generation, which is more expensive for the GC;
- needs synchronization, which causes contention with many threads;
- if you forget
reset(), the previous request's data leaks into the next one, which is a security bug; - objects that are never returned become a "leak".
When it's worth considering: very large buffers (Netty's PooledByteBufAllocator does this), direct memory, or when allocation really shows up as a problem in the profile. Measure allocation first with JFR or async-profiler, then decide.
About pool size: making a connection pool bigger doesn't make it faster. The database has limited cores, and 200 connections often run slower than 20. Measure the pool and watch the hikaricp_connections_pending metric.
With virtual threads, pooling threads loses its meaning too: you don't pool virtual threads, you limit the resource with a semaphore.
Sign up to mark studied questions and save your progress.