Multithreading 为什么异步请求在主线程结束时被销毁?春季任务

Multithreading 为什么异步请求在主线程结束时被销毁?春季任务,multithreading,spring,asynchronous,spring-integration,spring-io,Multithreading,Spring,Asynchronous,Spring Integration,Spring Io,我想写一个异步方法 @Component public class TaskImpl implements Task{ @Async(value="myExecutor") public void async(int n) throws InterruptedException{ log.info("Executing task"+n); Thread.sleep(1000); log.info("Finished executi

我想写一个异步方法

@Component
public class TaskImpl implements Task{

    @Async(value="myExecutor")
    public void async(int n) throws InterruptedException{
        log.info("Executing task"+n);
        Thread.sleep(1000);
        log.info("Finished executing task" +n);

    }

}
很好!我有这样的配置:

<task:annotation-driven executor="myExecutor" />    
<task:executor id="myExecutor" pool-size="3" />
我不想写加入或睡眠

问题2. 我需要async()方法来调用mail sender类。换句话说,我写了这个组件

@Component
public class MailMail {

    private MailSender mailSender;

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Async
    public void sendMail(String from, String to, String subject, String msg)   {

        ....
    }


    }
}

现在我感兴趣的是如何解决下面的问题。可能是沟通、网络问题,我无法发送电子邮件。现在发生了什么?如何捕获异常并再次发送?

对于测试用例,您可以
Mockito.spy
您的
TaskImpl
使用
doAnswer()
中的
CountDownLetch
并在测试方法结束时等待letch


对于这些异步任务的错误处理,您可以使用Spring Integration的
ErrorHandlingTaskExecutor
,并为其提供
ErrorHandler

谢谢!但我还有一个问题。在测试用例中,我也可以编写thread.join(),这不是问题。但在实际应用程序中,我应该倾听任务何时完成,然后销毁主线程。换句话说,当(任务正在执行){//waiting时,线程处于活动状态}
ThreadPoolTaskExecutor
has
waitfortaskstocompleteonshutton
waitterminationseconds
选项谢谢。但我只是调用接口方法。我不使用ThreadPoolTaskExecutor。我有XML格式的配置。我可以检索ThreadPoolTaskExecutor初始化对象吗?不使用该
而是直接从
WaitFortasksToCompleteShutton使用
ThreadPoolTaskExecutor
,它根本不会关闭java类。我想在一切都结束的时候关机。
2015-03-12 17:02:26.706  INFO ThreadPoolTaskExecutor: Shutting down ExecutorService
@Component
public class MailMail {

    private MailSender mailSender;

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Async
    public void sendMail(String from, String to, String subject, String msg)   {

        ....
    }


    }
}