velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Bojan Smojver <bo...@binarix.com>
Subject Re: Thread safety
Date Tue, 02 Oct 2001 04:57:41 GMT
"Geir Magnusson Jr." wrote:
> 
> On 10/1/01 4:24 AM, "Bojan Smojver" <bojan@binarix.com> wrote:
> 
> > Are Template.merge() and VelocityEngine.getTemplate() thread safe?
> >
> > Bojan
> 
> merge() is as long as you don't share a VelocityContext across simultaneous
> threads.
> 
> getTemplate() should be as well.

I'm making a fresh instance of the VC every time there is a new request.
Not the most efficient thing to do but rather simple. It's been
performing well on a P2 266, so I'll keep that for now.

> Er, why?  Problems?

No, the more I use Velocity, the better it gets... I just wanted to make
sure I'm doing the proper thing...

I'm not sure if you follow Tomcat Dev list, but there was a recent
report about problems with SingleThreadModel. I used to use it to ensure
thread synchro in my servlet, but after I read the code, I've realized
it would result in dreadful performance since the whole service method
would be synchronised.

I remember good old JServ which used pools, so I thought Tomcat was
doing the same. Which, of course, is utter nonsense, since they are two
totally different pieces of software.

Anyway, I've decided to go with non-SingleThreadModel servlet, but I
just have to be a bit more careful with a few things. When the (first
ever - for the container that supports pools) servlet instance in an
application is initiated, I create an instance of VelocityEngine and
store it into ServletContext. This VE is used by all servlet instances
(if pool approach is used by the container) or by all threads to
getTemplate(). If it's thread safe, I can have one of those and all is
fine. (Actually when I think about this a bit more, I would have had
problems when pool of servlets was used even if using SingleThreadModel,
provided getTemplate() wasn't thread safe)

Once the Template is fetched, it has to be merged by calling the merge()
method. Since this Template was fetched from the same instance of
VelocityEngine, it is possibly referring to the same object in its cache
as Template from some other thread/instance.

VelocityContext is always a local variable, created on the stack, so
freshness is guaranteed there. If there are no writes to Template by
merge() and no writes to VelocityEngine by getTemplate(), which can
upset this scenario, all should be fine.

Although I'm replying to Geir, I would like to thank all people that
spend their time contributing to this discussion.

Bojan

Mime
View raw message