So here is the problem. I have the following abstract class.
public abstract class JAXBParser<T> {
private static final Object lock = new Object();
private static volatile JAXBContext context;
private JAXBContext getContext() {
if (context == null) {
synchronized (getClass()) {
if (context == null) {
try {
context = JAXBContext.newInstance(getJAXBClass());
} catch (JAXBException e) {
log.error("Couldn't create JAXB context", e);
}
}
}
}
return context;
}
@SuppressWarnings("unchecked")
public Optional<T> parse(File file) {
log.debug(file.getAbsolutePath());
try {
JAXBContext context = getContext();
Unmarshaller unmarshaller = context.createUnmarshaller();
return Optional.ofNullable((T) unmarshaller.unmarshal(file));
} catch (JAXBException e) {
log.error(unmarshallerError(file.getAbsolutePath()), e);
}
return Optional.empty();
}
protected abstract Class getJAXBClass();
}
The idea is that I'll have couple of parsers with same behaviour so I can use this to follow the DRY principle (and to play with inheritance, multithreading, synchronization etc.). Also in this question it is stated that JAXBContext initialization is heavy, so it would be good idea to initialize it once. So I decided to initialize it once per child class using double-checked locking.
The question is the following:
Is it bad idea to use getClass() for synchronization? Would it be better to use lock object and why?