I’m building a singleton that has a ThreadLocal as an instance variable, this singleton has a method that may be accessed by multiple threads and it is lazily instantiated. Right now I’m thinking on something like this:
static final ThreadLocal<HashMap> bindingContext = new ThreadLocal<HashMap>();
But I’m not sure if it is a good idea, I also have the option to make it an instance variable since I’m using it (as I said on a singleton).
So the question is, where is the best place to initialize that class variable or should it be a class variable at all?
It is guaranteed that static initializers are executed in a thread safe way. The JLS specifically mentions this:
See section 12.4.2 of JLS that describes this very thing in detail.
EDIT: And what you are trying is perfectly fine. From the javadocs of ThreadLocal: