如果Spring批处理应用程序中存在非守护进程线程,当批处理终止时,应用程序永远不会关闭,即关机信号永远不会到达JVM。
这是意料之中的行为,还是Spring Batch由于故障而无法发送信号?
我附加了一个非常简单的应用程序,它再现了这个案例:https://github.com/ferblaca/SpringBatchDemo
版本: Spring boot 2.4.5 Spring Batch 4.3.2 Java 11
发布于 2021-05-25 03:27:17
这与Spring Batch无关。Spring Batch不会阻止您的JVM关闭。一旦您的作业完成,您的JVM就应该终止,否则会有其他因素阻止它关闭。在本例中,被配置为非守护进程线程的是您的executor服务。
我以你的例子为例,删除了所有与Spring Batch相关的东西,同样的事情也发生了:
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?。
https://stackoverflow.com/questions/67635470
复制相似问题