You are viewing a plain text version of this content. The canonical link for it is here.
Posted to soap-dev@xml.apache.org by "Matthew J. Duftler" <du...@watson.ibm.com> on 2001/05/17 19:57:06 UTC

Thread-safe use of DocumentBuilder?

I'm in the process of going through the JAXP integration to make sure
everything is thread-safe (and to clean it up a bit), and I'd like somebody
else's opinion on the following:

Most servlet engines create one instance of a particular servlet, or at
least they're supposed to, according to the Servlet spec. This one instance
can then be called by multiple threads. If there is one instance of a
DocumentBuilder within a particular servlet (which is the case with our
code), it is possible for that DocumentBuilder to be accessed by more than
one thread at a time. The JAXP spec says that implementations of the
DocumentBuilder abstract class are not deemed to be thread-safe.

While it is not all that appealing to create a new DocumentBuilder (i.e. a
parser) for each post, I don't see how it's thread-safe otherwise. Unless
there's a way to associate DocumentBuilder instances with the thread that
owns them (similar to associating attribute values with request, session,
application, etc...), I don't see a more efficient solution. (And tagging
the servlets with the SingleThreadModel interface I don't think is an
efficient solution.)

Opinions, suggestions, etc...?

Thanks,
-Matt


Re: Thread-safe use of DocumentBuilder?

Posted by Denis Haskin <dw...@earthlink.net>.
"Matthew J. Duftler" wrote:

> ...The JAXP spec says that implementations of the
> DocumentBuilder abstract class are not deemed to be thread-safe.
>
> While it is not all that appealing to create a new DocumentBuilder (i.e. a
> parser) for each post, I don't see how it's thread-safe otherwise. Unless
> there's a way to associate DocumentBuilder instances with the thread that
> owns them...

Hmm.  I see what you mean.  I did some initial tests and saw almost no cost to
DocumentBuilderFactory.newDocumentBuilder, but with a more realistic test, I
think there's lazy instantiation going on.  Reusing a DocumentBuilder was
faster than obtaining a new one.

Some other alternatives I can think of, though:
- put it in thread-local storage
- put it in a wrapper class to implement a SynchronizedDocumentBuilder (a la
Collections).
- maintain a synchronized pool of them for use by threads

other?...

dwh