users@jaxb.java.net

Re: Where does it say specifically that "Unmarshaller" instances are NOT thread-safe?

From: Adam Zell <zellster_at_gmail.com>
Date: Thu, 4 Feb 2010 16:49:10 -0800

Hello,

On Thu, Feb 4, 2010 at 4:32 PM, KARR, DAVID (ATTCINW) <dk068x_at_att.com>wrote:

> Does the JAXB specification or any javadoc specifically say that
> Unmarshaller (or Marshaller) objects are NOT thread-safe? I would
> assume they are not, but I would like to confirm that. The spec
> specifically talks about JAXBContext being thread-safe, but it doesn't
> say whether Unmarshaller/Marshaller is or not. The javadoc doesn't say,
> at least not that I've found.
>
>
From https://jaxb.dev.java.net/faq/index.html#threadSafety:

*Q. Are the JAXB runtime API's thread safe?*

A. The JAXB Specification currently does not address the thread safety of
any of the runtime classes. In the case of the Sun JAXB RI, the JAXBContext
class *is* thread safe, but the Marshaller, Unmarshaller, and Validator
classes *are not* thread safe.

For example, suppose you have a multi-thread server application that
processes incoming XML documents by JAXB. In this case, for the best
performance you should have just one instance of JAXBContext in your whole
application like this:

class MyServlet extends HttpServlet {
    static final JAXBContext context = initContext();

    private static JAXBContext initContext() {
        return JAXBContext.newInstance("....",MyServlet.class.getClassLoader());
    }

 And each time you need to unmarshal/marshal/validate a document. Just
create a new Unmarshaller/Marshaller/Validator from this context, like this:


    public void doGet( HttpServletRequest req, HttpServletResponse ) {
        Unmarshaller u = context.createUnmarshaller();
        u.unmarshal(...);
    }

 This is the simplest safe way to use the JAXB RI from multi-threaded
applications.

If you really care about the performance, and/or your application is going
to read a lot of small documents, then creating Unmarshaller could be
relatively an expensive operation. In that case, consider pooling
Unmarshaller objects. Different threads may reuse one Unmarshaller instance,
as long as you don't use one instance from two threads at the same time.


> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jaxb.dev.java.net
> For additional commands, e-mail: users-help_at_jaxb.dev.java.net
>
>


-- 
Adam
zellster_at_gmail.com