Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient method to process a String Freemarker syntax in Java

Here is our use case. We are loading freemarker syntax from the database and processing it. We are processing close to a million of records. Things are working fine. But when I profile the application, I see that my freemarker processing method is the bottleneck and it is taking most time. Having read the freemarker documentation, I got some pointers on what my issue would be. Everytime I am doing processing, I am creating new freemarker.template.Template object (creation of which seems expensive). I could not find what would be the right/more efficient way of doing this.


public FTLTemplateEngine() {
        cfg = new Configuration();      
    }    



public String process(String template, Map<String, Object> input) throws IOException, TemplateException {
        String rc = null;
        final Writer out = new StringWriter();      
        try {           
            final Template temp =new Template("TemporaryTemplate", new StringReader(template), cfg);
            temp.process(input, out);
        }
        catch (InvalidReferenceException e) {
                log.error("Unable to process FTL - " + template);
            throw new InvalidReferenceException("FTL expression has evaluated to null or it refers to something that doesn't exist.  - " + template, Environment.getCurrentEnvironment());
        }
        catch (TemplateException e) {
            log.error("Unable to process FTL - " + template);
            throw new TemplateException("Unable to process FTL - " + template, e, Environment.getCurrentEnvironment());
        }
        catch (IOException e) {
            log.error("Unable to process FTL - " + template);
            throw new IOException("Unable to process FTL - " + template);
        }
        rc = out.toString();
        out.close();
        return rc.trim();
    }   

Have a look the process method which is called every time Freemarker needs to be parsed. In this method we are creating new Template object everytime. Is there a way to avoid this?

like image 808
Anil Avatar asked Nov 09 '22 21:11

Anil


1 Answers

AFAIR you normally don't call the Template constructor directly, but use a Configuration instance to do that (see Get the template and Template loading). The Configuration object also employs caching, which could help. You might need to write your own TemplateLoader in order to load your FreeMarker templates from the database.

like image 71
Chaquotay Avatar answered Nov 14 '22 21:11

Chaquotay