We are using velocity to parse our templates.
Velocity developer guide suggests to create a new VelocityContext for every parsing
But what about the VelocityEngine
and the RuntimeInstances
?
Can we reuse them or is it better to create new instances every call ? Will the new instances of VelocityEngine cause memory leaks ?
public String parse(String templateStr, Map<String, String> params) {
StringWriter writer = new StringWriter();
try {
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
RuntimeServices rs = RuntimeSingleton.getRuntimeServices();
StringReader sr = new StringReader(templateStr);
SimpleNode sn = rs.parse(sr, "template");
Template t = new Template();
t.setRuntimeServices(rs);
t.setData(sn);
t.initDocument();
VelocityContext context = new VelocityContext();
if (params != null && !params.isEmpty()) {
for (Entry<String, String> entry : params.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
}
t.merge(context, writer);
} catch (Exception e) {
LOGGER.error("Exception in velocity parsing", e);
}
return writer.toString();
}
Velocity allows you to use Singleton model
Velocity.setProperty(Velocity.RUNTIME_LOG_NAME, "mylog"); Velocity.init(); Template t = Velocity.getTemplate("foo.vm");
Developers have two options for using the Velocity engine, the singleton model and the separate instance model. The same core Velocity code is used for both approaches, which are provided to make Velocity easier to integrate into your Java application.
Basically, instead of VelocityEngine, you can use Velocity class:
This class provides a separate new-able instance of the Velocity template engine. The alternative model for use is using the Velocity class which employs the singleton model.