As mentioned in the comments: There is no need to make every static field accessed by multiple threads thread local as long as the content of the field is known to be thread-safe. Good examples here are the typical immutable classes like String
, Integer
, ...
That said, you can wrap your ContentHandler
in a ThreadLocal
like this with Java8 and above:
private static final ThreadLocal<ContentHandler> ORG_OMG_xmi = ThreadLocal.withInitial(
() -> new RootXMLContentHandlerImpl("org.omg.xmi", new String[] { "xmi" },
"xmi", "http://schema.omg.org/spec/XMI/2.1", null));
pre Java8 you can achieve the same with this:
private static ThreadLocal<ContentHandler> ORG_OMG_xmi =
new ThreadLocal<ContentHandler>() {
@Override public ContentHandler initialValue() {
return new RootXMLContentHandlerImpl("org.omg.xmi", new String[] { "xmi" },
"xmi", "http://schema.omg.org/spec/XMI/2.1", null));
}
};
With ThreadLocal
every thread will get it's own instance of RootXMLContentHandlerImpl
which can be accessed by calling get()
on the ThreadLocal
:
ContentHandler myVeryThreadLocalContentHandler = ORG_OMG_xmi.get();