SyntaxHighlighter JS


XMLGregorianCalendar DatatypeFactory considered harmful

If you have ever worked with XML and JAXB, you will be familiar with XmlGregorianCalendar.  It is the default Java class that JAXB uses to represent XML date/time.  

A Java web service application I worked on experienced performance issues under load.  By simulating heavy SOAP request traffic with LoadUI and profiling with YourKit, I discovered the culprit was DatatypeFactory.

This particular SOAP web service response had at least fifty date/time fields. The code to construct the JAXB response naively called 


for each date/time field.

The call DatatypeFactory.newInstance() turns out to be very expensive. As shown in the JavaDoc

the newInstance method is a four step process with reflection.

Each time DatatypeFactory.newInstance() is called, Java has to rerun the four step discovery and creation process.

The obvious solution is to cache and reuse DatatypeFactory.newInstance(). I needed to confirm that the DatatypeFactory is thread-safe.  By doing a simple DatatypeFactory.newInstance().getClass().getName(), I discovered that the concrete implementation is

By looking at the source code at, I verified that newXMLGregorianCalendar() is thread-safe.

The implementation at line 201 is just

public XMLGregorianCalendar newXMLGregorianCalendar() {
    return new XMLGregorianCalendarImpl();

which is about as thread-safe as you can get.

Moral of Story: Do not call DatatypeFactory.newInstance() every time you need an XMLGregorianCalendar

Additional source

1 comment: