Java Concurrency Interview

Patterns and antipatterns question 156 of 180 senior

When would you choose an object pool, and when is it the wrong answer?

Pooling made sense when allocation was expensive and collectors were slow. On a modern JVM, allocating a short-lived object costs a pointer bump and dying young is nearly free, so pooling ordinary objects usually makes things worse: the pool itself is contended shared state, pooled objects are long lived and get promoted to the old generation, and every borrow risks a leak or a dirty object handed back with state left over.

It remains right when the resource is scarce or expensive beyond memory: database connections, sockets, threads, native handles, large direct byte buffers. Note what those have in common: the pool's real job is limiting concurrency against something external, not saving allocation.

If you do build one, the checklist is validation on borrow, a return in a finally, a bounded size, a timeout on acquisition, and eviction of idle entries.

patterns performance

Quiz yourself on Patterns and antipatterns Suggest a correction