“ThreadPoolTaskExecutor” 线程在春季执行后不会被终止

我正在尝试将 Quartz Sequential Execution 更改为 Parallel Execution。

它工作正常,性能明智,它似乎很好,但生成(创建)线程不会被破坏。

它仍然处于状态;为什么以及如何解决这个问题?请指导我。Runnable

enter image description here

代码在这里:

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        logger.error("Result Processing executed");
        List<Object[]> lstOfExams = examService.getExamEntriesForProcessingResults();
        String timeZone = messageService.getMessage("org.default_timezone", null, Locale.getDefault());
        if(lstOfExams!=null&&!lstOfExams.isEmpty()){
            ThreadPoolTaskExecutor threadPoolExecuter = new ThreadPoolTaskExecutor();
            threadPoolExecuter.setCorePoolSize(lstOfExams.size());
            threadPoolExecuter.setMaxPoolSize(lstOfExams.size()+1);
            threadPoolExecuter.setBeanName("ThreadPoolTaskExecutor");
            threadPoolExecuter.setQueueCapacity(100);
            threadPoolExecuter.setThreadNamePrefix("ThreadForUpdateExamResult");
            threadPoolExecuter.initialize();

            for(Object[] obj : lstOfExams){
                if(StringUtils.isNotBlank((String)obj[2]) ){
                    timeZone = obj[2].toString();
                }
                try {
                    Userexams userexams=examService.findUserExamById(Long.valueOf(obj[0].toString()));
                    if(userexams.getExamresult()==null){
                        UpdateUserExamDataThread task=new UpdateUserExamDataThread(obj,timeZone);
                        threadPoolExecuter.submit(task);
                    }
//                  testEvaluator.generateTestResultAsPerEvaluator(Long.valueOf(obj[0].toString()), obj[4].toString(), obj[3]==null?null:obj[3].toString(),timeZone ,obj[5].toString() ,obj[1].toString()); 
//                  logger.error("Percentage Marks:::::"+result.getPercentageCatScore());
                } catch (Exception e) {
                    Log.error("Exception at ResultProcessingJob extends QuartzJobBean executeInternal(JobExecutionContext context) throws JobExecutionException",e);
                    continue;
                }

            }
            threadPoolExecuter.shutdown();
        }
}

UpdateUserExamDataThread .class

@Component
//@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
//public class UpdateUserExamDataThread extends ThreadLocal<String> //implements Runnable {
public class UpdateUserExamDataThread implements Runnable {
    private Logger log = Logger.getLogger(UpdateUserExamDataThread.class);
    @Autowired
    ExamService examService;
    @Autowired
    TestEvaluator testEvaluator;
    private Object[] obj;
    private String timeZone;


    public UpdateUserExamDataThread(Object[] obj,String timeZone) {
        super();
        this.obj = obj;
        this.timeZone = timeZone;
    }

    @Override
    public void run() {
        String threadName=String.valueOf(obj[0]);
        log.info("UpdateUserExamDataThread Start For:::::"+threadName);
        testEvaluator.generateTestResultAsPerEvaluator(Long.valueOf(obj[0].toString()), obj[4].toString(), obj[3]==null?null:obj[3].toString(),timeZone ,obj[5].toString() ,obj[1].toString());
        //update examResult
        log.info("UpdateUserExamDataThread End For:::::"+threadName);
    }

}

TestEvaluatorImpl.java

@Override
    @Transactional
    public Examresult generateTestResultAsPerEvaluator(Long userExamId, String evaluatorType, String codingLanguage,String timeZoneFollowed ,String inctenceId ,String userId) {
        dbSchema = messageService.getMessage("database.default_schema", null, Locale.getDefault());

        try {
//Some Methods
return examResult;
}catch(Exception e){
log.erorr(e);
}
}

如果需要,我可以提供线程转储文件。


答案 1

似乎您在相同规模的考试中创建线程池,这并不是最佳的。

    // Core pool size is = number of exams  
    threadPoolExecuter.setCorePoolSize(lstOfExams.size());

    // Max pool size is just 1 + exam size. 
    threadPoolExecuter.setMaxPoolSize(lstOfExams.size()+1);

你必须考虑这一点: - 如果你创建了一个线程池并启动了它,那么核心大小中定义的线程数会立即启动。

  • 仅当您提交的核心池线程现在可以处理的多于队列大小已满(在本例中为 100)时,最大池大小才有效。因此,这意味着只有当提交的任务数量超过 100+考试大小时,才会创建新线程。

在你的例子中,我会将核心池大小设置为5或10(这实际上取决于目标CPU有多少个核心和/或IO绑定提交的任务的方式)。

最大池大小可以是此值的两倍,但在队列已满之前不会生效。

要在提交的工作完成后减小活动线程的大小,您必须设置 2 个参数。

  • setKeepAliveSeconds(int keepAliveSeconds): 如果线程未在定义的秒数(默认为 60 秒,这是最佳)使用,则允许线程自动关闭,但这通常仅用于关闭非核心池线程的线程。

  • 要在 keepAliveSeconds 之后关闭核心部分的线程,您必须将 setAllowCoreThreadTimeOut(布尔值 allowCoreThreadTimeOut) 设置为 true。只要应用程序正在运行,这通常就是保持核心池处于活动状态是错误的。

我希望它有帮助。


答案 2

我怀疑您的一个线程无限期地等待IO请求答案。例如,您尝试连接到未设置连接超时且主机未应答的远程主机。在这种情况下,您可以通过运行底层的方法强制关闭所有正在执行的任务,然后您可以分析由违规线程引发的中断IOExceptionshutdownNowExecutorService

取代

threadPoolExecuter.shutdown();

与下面,以便您可以检查错误。

ExecutorService executorService = threadPoolExecuter.getThreadPoolExecutor();
executorService.shutdownNow();

这将向所有正在运行的线程发送中断信号。