3

I use SAX to parse a big xml file which is big and has many many repeated node. And use JAXB to map the parsed and repeated dom nodes to javabeans for persistence.

Here is my code fragment. I use JAXB's partial unmarshalling example code, it create Unmarshaller object each time a node parsing is started. Can i reuse it for one whole xml parsing or cache it for multiple xml parsing?

public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    ...

    if (namespaceURI.equals("") && localName.equals( “product” )) {
        Unmarshaller unmarshaller = null;
        try {
            //I want to reuse it, not create it in each startElement method
            unmarshaller = jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new SAXException(e);
        }
    ...

1 Answer 1

7

As long as your JAXBContext doesn't change, you can reuse the unmarshaller.

See also the Javadoc for JAXBContext. It contains an example that reuses the same unmarshaller for mulitple XML files, only when the context (the package of BazObject is not on the context path) changes, you'd need to create a new unmarshaller from a different context.

3
  • 6
    Should also be noted that the Unmarshaller that is created is not threadsafe and should be wrapped in a ThreadLocal if accessed by multiple threads.
    – David
    Mar 21, 2013 at 8:54
  • @moxn @ Chunkz What about to reuse UnmarshallerHandler got from Unmarshaller?
    – Henry Leu
    Mar 21, 2013 at 9:01
  • The javadoc for the class says that it's reusable as a ContentHandler... But my guess is that it itself is not threadsafe either.
    – David
    Mar 21, 2013 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.