Hi, This is a copy of the issue created here: https://github.com/spring-projects/spring-batch/issues/3725 by @martinmogusu
Bug description I notice that a spring boot batch application does not shut down automatically after completing a job when using Spring data JPA. The job completes successfully but the spring boot application remains running and has to be stopped manually (e.g. by pressing Ctrl + C).
Environment Spring boot version: 2.3.0.RELEASE Java version: 1.8 OS: Ubuntu 18.04
Steps to reproduce git clone https://github.com/spring-guides/gs-batch-processing Remove everything but keep only the complete folder.
Add the following dependencies: spring-boot-starter-batch
In the complete-jpa/src/main/java/com/example/batchprocessing/BatchConfiguration.java file
Replace the JdbcBatchItemWriter by a JpaItemWriter
@Bean
public ItemWriter<Person> writer(LocalContainerEntityManagerFactoryBean entityManagerFactory) {
JpaItemWriter<Person> writer = new JpaItemWriter<>();
writer.setEntityManagerFactory(Objects.requireNonNull(entityManagerFactory.getObject()));
return writer;
}
@Bean
public Step step1(ItemWriter<Person> writer) {
return stepBuilderFactory.get("step1")
.<Person, Person> chunk(10)
.reader(reader())
.processor(processor())
.writer(writer)
.build();
}
In the Person class, add the JPA annotation and the id field:
`@Entity public class Person {
@Id
@GeneratedValue
private Long id;`
Replace the artifact version of spring-boot-starter-parent with 2.2.8.RELEASE
mvn clean package and the run it. There is no problem. You can find this version here: https://github.com/florentbo/spring-boot-batch-jpa-bug
Then replace the artifact version of spring-boot-starter-parent with 2.3.0.RELEASE The job completes successfully but the spring boot application remains running and has to be stopped manually (e.g. by pressing Ctrl + C).
Comment From: wilkinsona
Thanks for the sample. The JVM is kept alive by two non-daemon threads that are created by the asynchronous bootstrapping of Data JPA repositories. You can switch back to Spring Boot 2.2's behaviour where this bootstrapping was performed synchronously by adding spring.data.jpa.repositories.bootstrap-mode=default
to application.properties
. With the configuration in place, the JVM shuts down once the job has completed.
Comment From: wilkinsona
On second thoughts, this isn't a regression. It's a bug in the guide that the switch to async bootstrapping of Hibernate has exposed. Anything else in the app that made use of the context's task executor would also have caused the problem.
When you want the context to close and the application to exit, you should at least call close()
rather than relying on the JVM exiting automatically as there a no non-daemon threads running. You may also want to go a step further and use System.exit
and SpringApplication.exit
as described in the documentation.