SpringTemplateEngine process with parallelStream

56 Views Asked by At

I am trying to process multiple thymeleaf templates with parallel streams in java. I am using springboot 2.7.17 with thymeleaf-spring5 3.0.15 an java 17.

Problem is that I will get multiple: SpelEvaluationException: EL1011E: Method call: Attempted to call method 'xy' on null context object` where xy is any function e.g. #lists.isEmpty, #strings.equals etc.

Here is SpringTemplateEngine configuration:

SpringTemplateEngine templateEngine = new SpringTemplateEngine();

        templateEngine.addTemplateResolver(defaultTemplateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        HashSet<IDialect> additionalDialects = new HashSet<>(Arrays.asList(
                new LayoutDialect(),
                new CgDialect(),
                new StripWhitespaceDialect(),
                new GaDialect()));
        templateEngine.setAdditionalDialects(additionalDialects);
        templateEngine.setMessageResolver(new SpringMessageResolver());
        templateEngine.setMessageSource(messageSource);

Here is how I configured my WebContext:

WebContext ctx = new WebContext(pageModel.getRequest(), pageModel.getResponse(), context, pageModel.getLocale());
ctx.setVariables(pageModel.getModel());
ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, new ThymeleafEvaluationContext(applicationContext, new DefaultFormattingConversionService()));

RequestContext requestContext = new RequestContext(pageModel.getRequest(), pageModel.getResponse(), context, pageModel.getModel());
ctx.setVariable(SpringContextVariableNames.SPRING_REQUEST_CONTEXT, requestContext);

SpringWebMvcThymeleafRequestContext thymeleafRequestContext = new SpringWebMvcThymeleafRequestContext(requestContext, pageModel.getRequest());
ctx.setVariable(SpringContextVariableNames.THYMELEAF_REQUEST_CONTEXT, thymeleafRequestContext);

And this is execution:

templateList.parallelStream().forEach(templateName -> {
            System.out.println(templateEngine.process(templateName, ctx));
        });

WebContext has all variables it needs and this code works if I run it sequentially without parallelStream.

I hope parallel stream would render multiple results faster.

What I don't understand is: Why it seams that template doesn't have context if I pass the same context for every execution of process method? Is Spring template engine intended to be used on multiple threads?

Thank you for any suggestion and help.

0

There are 0 best solutions below