Reputation: 342
I have a large number of threads which use a static variable, which is lazily initialized in a synchronized block. The initialization is memory intensive so ideally would like to do this once only. I understand that threads access their own cached copy of a static variable but it takes some time before it's cached, so initially every thread is entering the initialization block. Even if it's synchronized, this can cause an out of memory error.
Is there a way to force the static variable to be available to all new threads as soon as it's initialized by the first thread?
Code (simplified):
class TestingThread extends Thread {
private static Templates transformTemplateRequest = null;
private static final Object lockObj = new Object();
private Document xslt;
public void run() {
//Document xslt initialized
Transformer requestTransformer = null;
synchronized (lockObj) {
if (transformTemplateRequest == null) {
TransformerFactory tf = TransformerFactory.newInstance();
Source xsltSource = new DOMSource(xslt);
transformTemplateRequest = tf.newTemplates(xsltSource);
}
}
requestTransformer = transformTemplateRequest.newTransformer();
//other work
}
}
Upvotes: 2
Views: 319
Reputation: 16392
I'd just wrap this in another if stmt:
if (transformTemplateRequest == null) {
synchronized (lockObj) {
if (transformTemplateRequest == null) {
TransformerFactory tf = TransformerFactory.newInstance();
Source xsltSource = new DOMSource(xslt);
transformTemplateRequest = tf.newTemplates(xsltSource);
}
}
}
this bypasses the synchronized block entirely if the variable is already set.
Upvotes: 1