Sub topic 16
Lifecycle and SmartLifecycle for Start and Stop
This chapter assumes you know the init and destroy callbacks from earlier chapters (@PostConstruct, @PreDestroy, InitializingBean, DisposableBean). It also assumes you know singleton scope and can run a Spring or Spring Boot application.
Init and destroy callbacks tie work to a bean's creation and removal. Some components need something different: a message listener, a polling thread, or a scheduler that can be started and stopped while the context stays alive. Spring models this with the Lifecycle and SmartLifecycle interfaces.
Creation versus running
A bean is created once. A component can be started and stopped more than once during the life of the context. @PostConstruct runs during bean creation, before the application is fully assembled. Starting a thread or opening a consumer there means it can begin work while other singletons are still being created.
The lifecycle interfaces move that work to a later point. The container starts them after every singleton exists, and it stops them before it destroys any singleton.
| Mechanism | When it runs | Can run repeatedly | Ordered across beans |
|---|---|---|---|
| `@PostConstruct` / `afterPropertiesSet` | During bean creation | No, once per bean | By dependency only |
| `Lifecycle` | On explicit `ctx.start()` and on `ctx.stop()` or close | Yes | By phase (0 by default) |
| `SmartLifecycle` | Automatically at refresh, and on close | Yes | By phase |
| `@PreDestroy` / `destroy` | After all stops, during singleton destruction | No | Reverse dependency order |
The Lifecycle interface
org.springframework.context.Lifecycle declares three methods:
start()begins the component.stop()ends it.isRunning()reports the current state.
The container asks isRunning() before it calls start() or stop(). A wrong answer causes missed or repeated calls, so keep the state in a thread-safe field.
Plain Lifecycle beans are not started when the context refreshes. They start only when you call ApplicationContext.start() yourself. Spring Boot does not call start() on its context either, so a plain Lifecycle bean in a Boot application never starts unless your code calls it. For most cases, use SmartLifecycle.
SmartLifecycle
SmartLifecycle extends Lifecycle and Phased. It adds three things:
isAutoStartup()defaults totrue. When it is true, the container starts the bean at the end of context refresh.getPhase()sets the ordering. The default isSmartLifecycle.DEFAULT_PHASE, which isInteger.MAX_VALUE, so default beans start last and stop first.stop(Runnable callback)is an asynchronous stop. The default implementation callsstop()and thencallback.run().
Startup runs in ascending phase order. Shutdown runs in descending phase order, so the component that started last stops first. Within one phase, Spring respects dependencies. A bean that depends on another starts after it and stops before it.
A worked example
This program has one SmartLifecycle bean with a polling thread, and one plain Lifecycle bean.
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.context.Lifecycle;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
class PollingWorker implements SmartLifecycle {
private final AtomicBoolean running = new AtomicBoolean(false);
private volatile Thread thread;
@Override
public void start() {
if (running.compareAndSet(false, true)) {
thread = new Thread(this::loop, "polling-worker");
thread.start();
System.out.println("PollingWorker started");
}
}
private void loop() {
while (running.get()) {
System.out.println("polling...");
try {
Thread.sleep(400);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
@Override
public void stop() {
if (running.compareAndSet(true, false)) {
Thread t = thread;
t.interrupt();
try {
t.join(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("PollingWorker stopped");
}
}
@Override
public boolean isRunning() {
return running.get();
}
@Override
public int getPhase() {
return 100;
}
}
class ManualTask implements Lifecycle {
private volatile boolean running;
@Override
public void start() {
running = true;
System.out.println("ManualTask started");
}
@Override
public void stop() {
running = false;
System.out.println("ManualTask stopped");
}
@Override
public boolean isRunning() {
return running;
}
}
public class LifecycleDemo {
public static void main(String[] args) throws InterruptedException {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(PollingWorker.class, ManualTask.class)) {
System.out.println("context refreshed");
Thread.sleep(1000);
ctx.start();
Thread.sleep(500);
}
}
}Typical output:
PollingWorker started
polling...
context refreshed
polling...
polling...
ManualTask started
polling...
ManualTask stopped
PollingWorker stoppedPollingWorker starts during refresh without any call from you. ManualTask starts only at ctx.start(). On close, ManualTask (phase 0) was started before PollingWorker (phase 100), so it stops after it in a strict phase ordering. Here it prints first because of how close handles beans started by ctx.start(), so do not depend on the order of two components in different phases unless you set the phases yourself.
Asynchronous stop and the shutdown timeout
A component such as a message consumer may need time to finish in-flight work. Calling stop() and blocking works, but beans in the same phase are then stopped one after another. stop(Runnable callback) lets the container stop all beans of one phase in parallel. Each bean signals completion by running the callback.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.context.SmartLifecycle;
public class DrainingConsumer implements SmartLifecycle {
private final AtomicBoolean running = new AtomicBoolean(false);
@Override
public void start() {
running.set(true);
}
@Override
public void stop() {
running.set(false);
}
@Override
public void stop(Runnable callback) {
CompletableFuture
.runAsync(this::drainInFlightWork)
.whenComplete((result, error) -> {
running.set(false);
callback.run();
});
}
private void drainInFlightWork() {
// finish pending messages here
}
@Override
public boolean isRunning() {
return running.get();
}
@Override
public int getPhase() {
return 200;
}
}The container waits for the callbacks of each phase before it moves to the next phase. The wait is bounded by a timeout per shutdown phase. DefaultLifecycleProcessor defaults to 10 seconds, and Spring Boot sets it to 30 seconds. You can change it with spring.lifecycle.timeout-per-shutdown-phase. When the timeout expires, the container logs a message and moves on, which can leave work unfinished.
Choosing phases
Phases are plain integers. Pick them so that a producer starts after the thing it needs and stops before it.
- Use a low phase for infrastructure that others rely on, such as a connection manager. It starts first and stops last.
- Use a higher phase for components that accept work, such as listeners. They start last and stop first, so no new work arrives while their dependencies shut down.
- Spring's own lifecycle beans, for example the embedded web server in Spring Boot, also have phases. A bean with the default phase may start after the server accepts traffic. If your bean must be ready before requests arrive, choose a lower phase explicitly, and check the framework's phases for your version before you choose numbers.
Common errors
- Blocking in
start().start()runs on the thread that refreshes the context. A loop that never returns hangs startup. Start a thread or submit a task, then return. - Doing the work in
@PostConstructinstead. Work started there can run before other singletons are ready, and it cannot be stopped and restarted. - Expecting plain
Lifecycleto auto-start. Nothing starts it unlessisAutoStartup()exists, which means usingSmartLifecycle, or your code callsctx.start(). - A wrong
isRunning(). If it returnsfalsefor a running component,stop()is skipped and the thread keeps running at shutdown. - Exceptions in
start(). They propagate and fail the context refresh. Catch exceptions you can recover from. - Assuming prototypes take part. The container does not manage prototype beans after creating them, so it never starts or stops them.
Exercise
A SmartLifecycle bean has phase 50 and another has phase 300. In what order are they started and stopped, and why does that order suit a producer that sends messages to a consumer?
Show answer
The phase 50 bean starts first and stops last. The phase 300 bean starts last and stops first. Give the consumer the lower phase and the producer the higher phase. The consumer is then running before the producer sends anything, and during shutdown the producer stops first, so no message arrives after the consumer has stopped.
Exercise
Your SmartLifecycle implements stop(Runnable callback) but a bug leaves a branch where callback.run() is never called. What do you observe at shutdown, and what is the fix?
Show answer
The container waits for the whole shutdown timeout for that phase (10 seconds by default, 30 in Spring Boot), logs that the bean did not stop in time, and then continues. The fix is to call callback.run() on every path, for example in a whenComplete handler or a finally block.