Skip to content

Commit

Permalink
Added caching of DatatypeFactory instances to ConstructionStrategies (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
amohrig authored and garethahealy committed Dec 17, 2019
1 parent 506403b commit 2114be1
Showing 1 changed file with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -409,19 +409,24 @@ private static <T> T newInstance(Class<T> clazz) {

private static class XmlGregorian implements BeanCreationStrategy {

// Instantiating a DatatypeFactory with DatatypeFactory.newInstance() is expensive, so this should be cached.
// Regrettably the spec does not require implementations to be thread safe, so we are defensively using
// thread local caching here.
private static final ThreadLocal<DatatypeFactory> datatypeFactoryHolder = ThreadLocal.withInitial(() -> {
try {
return DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new MappingException(e);
}
});

public boolean isApplicable(BeanCreationDirective directive) {
Class<?> actualClass = directive.getActualClass();
return XMLGregorianCalendar.class.isAssignableFrom(actualClass);
}

public Object create(BeanCreationDirective directive) {
DatatypeFactory dataTypeFactory;
try {
dataTypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new MappingException(e);
}
return dataTypeFactory.newXMLGregorianCalendar();
return datatypeFactoryHolder.get().newXMLGregorianCalendar();
}

}
Expand Down

0 comments on commit 2114be1

Please sign in to comment.