users@jersey.java.net

Re: [Jersey] singleton resources

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Thu, 29 Oct 2009 08:57:58 +0100

On Oct 29, 2009, at 3:05 AM, Tatu Saloranta wrote:

> On Wed, Oct 28, 2009 at 4:12 PM, Zoltan Arnold NAGY <Zoltan.Nagy_at_sun.com
> > wrote:
>> Hi,
>>
>> if I understand correctly, unless I annotate a resource class with
>> @Singleton, it's going to
>> be created on a per-request basis, then discarded. Is that correct?
>>
>> If it is, doesn't it introduces a performance penalty?
>>
>> If all of my methods on my resource class are thread-safe, then
>> going with a
>> singleton
>> might yield better performance.
>
> It all depends on how expensive constructing said resource is. Just
> constructing simple Java objects is very cheap all things considered
> (you can create millions of temporary objects per second; yet most
> services can't push more than hundreds of requests through, at least
> if there's a DB involved).
> So creating couple of extra objects per request is onlt worth
> optimizing for unless these objects are expensive to create or
> initialize. On plus side, per-thread instances need no synchronization
> and are simpler to deal with.
>

Right. The per-request programing model for resource classes is often
better than the per-singleton programming model. And one could use DI
to obtain references to expensive resources.

You might be surprised at how many Java objects will be created to
process an HTTP request and produce response :-)

Paul.