Question

I'm starting to learn Java with Spring and I've written some simple scheduled tasks.

I don't understand the mechanism that the framework uses so the application does not exit after the getBean call. How come the application keeps on printing "Hi"?

public class Application {

    public static void main(String[] args) {
        ...
        PeriodicTask task = appCtx.getBean(PeriodicTask.class);
    }
}
public class PeriodicTask {

    @Scheduled(fixedRate = 5000)
    public void periodic() {
        System.out.println("Hi");
    }
}
Was it helpful?

Solution

Given @Scheduled, I'm going to assume your ApplicationContext has some scheduled configuration. This means that your are creating (implicitly or explicitly) a SchedulerExecutorService which spawns non-daemon threads. The application will not end until all non-daemon threads have completed. One of these threads is executing your periodic method every 5000 milliseconds.

Now, you could put your ApplicationContext instantiation in a try-with-resources. Once execution leaves the try block, the ApplicationContext would be closed, shutting down the ScheduledExecutorService and eventually terminating your program.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top