使用ExecutorService执行异步任务时出现问题
快速回顾一下-我有一个Java
EE前端,可以接受用户请求,然后针对每个请求使用ExecutorService(SingleThreadedExecutor设置为守护程序)启动冗长的工作流,该工作流包含在库中并且可以工作很好,并且在通过Eclipse以独立模式运行时按预期运行。当从website(servlet)调用时,我观察到工作流始终在初始化Velocity
Engine(Velocity.init()或ve.init())时挂起。因此,我前面提到的问题。
当所有答案/建议都无效时,我推断这与Velocity的启动方式有关,并决定改用FreeMarker。现在,我看到FreeMarker实现的工作流程也被挂在了完全相同的位置。这个``地方’‘是邮件构建的一部分,它根据大量传递的数据对象评估模板并返回邮件字符串。调用Freemark’ing类和FreeMark类的类如下-
   public class mailBuilder {    private static final Logger log = Logger.getLogger( mailBuilder.class );    
    static String a;
    static String b;
    public mailBuilder(CustomDataStructure input)
    {
        a = input.getA();
        b = input.getB(); 
    }
    public static String returnMailstring() throws Exception
    {
        log.info("Gathering elements to construct email.");
        String mailText=null;
        Map context = new HashMap();
        context.put("a",a);
        context.put("b",b);
        log.info("Calling Freemarker");
        mailText=FreeMarkIT.ReturnReportString(context);
        log.info("Freeemarker returned string");
        return mailText;
    }
}
FreeMarkIT类如下-
    public class FreeMarkIT {        private static final Logger log = Logger.getLogger( FreeMarkIT.class );
        private static Configuration config;
        private static Template template;
        public static String ReturnReportString(Map model) throws IOException, TemplateException
        {
            StringWriter sw = new StringWriter();
            try 
            {
               log.info("Going to get the template");
               config= new Configuration();
               log.info("Now really");
               template=config.getTemplate("src/resource/email_template.vm");
               log.info("Done initializing template");
               template.process(model, sw);
               sw.flush();
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
            return sw.getBuffer().toString();
        }
    }
现在,从我的日志记录看来,工作线程挂在了该行 config=new Configuration()
同样,从Eclipse运行时,它可以在独立模式下按预期方式工作,但是当使用ExecutorService从servlet调用时,则挂起。
我开始思考/意识到这可能与Velocity或FreeMarker无关,而与ExecutorService无关。任何建议或建议都会有很大帮助。
谢谢
回答:
你的代码是不是线程安全的,因为你是共享config和template跨所有线程实例(不断重新设置它们)。使它成为线程安全的最简单方法是在方法中使用config和template局部变量,而不是静态成员。作为@JBNizet在评论中指出,你有类似的问题mailBuilder与a和b。您可能想先阅读一些有关面向对象编程基础的教程,然后再回过头看这个问题(提示,通常应避免使用除常量以外的静态成员变量)。
以上是 使用ExecutorService执行异步任务时出现问题 的全部内容, 来源链接: utcz.com/qa/421876.html








