首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring批处理和非守护进程线程

Spring批处理和非守护进程线程
EN

Stack Overflow用户
提问于 2021-05-21 18:54:10
回答 1查看 86关注 0票数 0

如果Spring批处理应用程序中存在非守护进程线程,当批处理终止时,应用程序永远不会关闭,即关机信号永远不会到达JVM。

这是意料之中的行为,还是Spring Batch由于故障而无法发送信号?

我附加了一个非常简单的应用程序,它再现了这个案例:https://github.com/ferblaca/SpringBatchDemo

版本: Spring boot 2.4.5 Spring Batch 4.3.2 Java 11

EN

回答 1

Stack Overflow用户

发布于 2021-05-25 03:27:17

这与Spring Batch无关。Spring Batch不会阻止您的JVM关闭。一旦您的作业完成,您的JVM就应该终止,否则会有其他因素阻止它关闭。在本例中,被配置为非守护进程线程的是您的executor服务。

我以你的例子为例,删除了所有与Spring Batch相关的东西,同样的事情也发生了:

代码语言:javascript
复制
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class DemoBatchApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder().sources(com.example.demo.batch.DemoBatchApplication.class)
            .web(WebApplicationType.NONE)
            .run(args);
    }

    private final ScheduledExecutorService scheduledExecutorService = Executors
            .newSingleThreadScheduledExecutor(new BasicThreadFactory.Builder()
                    .namingPattern("task-non-daemon-%d")
                    .daemon(false)
                    .build());

    @PostConstruct
    public void init() {
        this.scheduledExecutorService.scheduleAtFixedRate(() -> {
            System.out.println("Scheduled task non-daemon!!!!");
        }, 1L, 1000L, TimeUnit.MILLISECONDS);
    }
    
}

如果您运行此应用程序,您应该看到相同的行为:scheduledExecutorService将继续运行,因为您将其设置为非守护进程线程。如果您将守护程序标志更改为true,则JVM将在您的作业完成后立即停止。请查看What is a daemon thread in Java?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67635470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档