Thread-local variables in Java (ctd)

On the previous page, we saw an example of using ThreadLocal to pool Calendar objects. On this page, we consider what are the general criteria for choosing ThreadLocal?

When to use ThreadLocal?

So what are other good candidates for object re-use via ThreadLocal? Basically, objects where:

That means that typical objects to use with ThreadLocal could be:

Note that it is generally better not to re-use objects that are trivial to construct and finalize. (By "trivial to finalize", we mean objects that don't override finalize.) This is because recent garbage collector implementations are optimised for "temporary" objects that are constructed, trivially used and then fall out of scope without needing to be added to the finalizer queue. Pooling something trivial like a StringBuffer, Integer or small byte array can actually degrade performance on modern JVMs.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.