[stringtemplate-interest] Thread safety of templates - am I correct in thinking getInstanceOf?

Terence Parr parrt at cs.usfca.edu
Tue Oct 23 18:28:56 PDT 2007


On Oct 24, 2007, at 8:09 AM, Steven Atkinson wrote:

> Hi folks,
>
>
>
> I am a long-time ANTLR user but I am new to StringTemplate, and  
> need to use it in anger soon now.

Hi Steve :)
>  I have about 500 StringTemplate objects that I am loading in to  
> memory on demand (caching).

okidoki.
> In my application at any time I will have multiple threads needing  
> to supply their own attributes and use each of these 500 templates.

Should be no problem as each thread will need it's own template  
instance.  For example, each page request in a server will create a  
template instance to fill.  Separate threads should set attributes  
only in different template instances.
> I do this so that I am not re-chunking the templates each time they  
> are used.

That is good.  That is a readonly and shared data structure once ST  
parses it.  Instances are just walking those chunks when necessary,  
using separate attribute tables.
>  To handle multiple threads needing to supply differing attributes  
> to the same StringTemplate at the same time,
Oh!  This is different.
> it looks like I should be using StringTemplate.getInstanceOf to re- 
> use the chunks but have different attributes.

That doesn't rechunk. It just creates a new template instance with a  
new attribute table.
>  i.e.
>
>
>
> String clientThreadMethod() {
>
>    StringTemplate template = // find one of the cached 500 templates;
>
>    StringTemplate instanceST = template.getInstanceOf();
>
>    instanceST.setAttribute(“name”, “foo”);
>
>>
>    return instanceST.toString();
>
> }

Not a problem as it will get a new attrib table. (hashtable).
>  This would seem to work just fine until we have nested templates  
> to consider – a quick reading through the code makes me think that  
> instanceSTs are created to handle nested template references, but I  
> just wanted to check in with the group to see whether this is true,  
> and also just check that sharing the chunks and keeping the  
> attributes per-thread was the way to go for using StringTemplate in  
> a high-volume multi-threaded shared-StringTemplate environment.
Yep. Done by sites easily doing 1.5M page views a day.

I've never needed to push attribs into the same template from diff.  
threads.  That can be done too by collecting hashtable outside of ST  
and then pushing in all at once.

Ter



More information about the stringtemplate-interest mailing list