users@jersey.java.net

Re: [Jersey] Thread safety of XML-based factories <was> Re: [Jersey] Fixed <was> Re: [Jersey] Jersey vulnerable to XXE attack?

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Mon, 13 Jul 2009 10:37:13 -0700

On Mon, Jul 13, 2009 at 6:15 AM, Martin Probst<mail_at_martin-probst.com> wrote:
>> Given we are close to releasing i have taken the conservative step of
>> creating and storing factories in thread locals.
>
> Why do you bother with caching them anyways?
>
> If it's for performance reasons, I would suggest to implement the
> simple solution (new factory on every request), then measure, and then
> maybe do something about it. As far as I can see there is nothing
> expensive at least in DocumentBuilderFactory.

Because construction of these factories is VERY inefficient. Or
rather, not construction, but locating actual implementation using the
convoluted logic, which essentially may go through every single
(possibly compressed) jar file within your classpath, looking for
WEB-INF/resources file that contains relevant setting(s).
You can measure this to see how much it's for your specific
environment; typical numbers are in two-digit milliseconds.

As to reusability, despite all claims to contrary, I have yet to see a
case where it would be anything but "safe-after-you-have-configured
it".

That is: what I do is that iff I can configure factory instance up
front, instance will be thread-safe after this. What this means, then,
is that either

(a) factory must be created eagerly when app/service starts, OR
(b) accessor must be synchronized, if lazy instantiation is needed.

Creating a factory per ThreadLocal is not a good solution mostly
because some resources (symbol tables, possibly low-level buffers) are
retained on per-factory basis. As such, you can have 150x (or
whatever, max number of concurrent threads ever needed) copies of
these for app server.

But if this is done, ThreadLocals should use soft references to refer
to factory. That allows GC to dump them if and as needed. That's an ok
approach.

-+ Tatu +-