[[jmx-shutdown]]
= Orderly Shutdown

As described in "xref:jmx.adoc#jmx-mbean-exporter[MBean Exporter]", the MBean exporter provides a JMX operation called `stopActiveComponents`, which is used to stop the application in an orderly manner.
The operation has a single `Long` parameter.
The parameter indicates how long (in milliseconds) the operation waits to allow in-flight messages to complete.
The operation works as follows:

. Call `beforeShutdown()` on all beans that implement `OrderlyShutdownCapable`.
+
Doing so lets such components prepare for shutdown.
Examples of components that implement this interface and what they do with this call include JMS and AMQP message-driven adapters that stop their listener containers, TCP server connection factories that stop accepting new connections (while keeping existing connections open), TCP inbound endpoints that drop (log) any new messages received, and HTTP inbound endpoints that return `503 - Service Unavailable` for any new requests.
. Stop any active channels, such as JMS- or AMQP-backed channels.
. Stop all `MessageSource` instances.
. Stop all inbound `MessageProducer` s (that are not `OrderlyShutdownCapable`).
. Wait for any remaining time left, as defined by the value of the `Long` parameter passed in to the operation.
+
Doing so lets any in-flight messages complete their journeys.
It is therefore important to select an appropriate timeout when invoking this operation.
. Call `afterShutdown()` on all `OrderlyShutdownCapable` components.
+
Doing so lets such components perform final shutdown tasks (closing all open sockets, for example).

As discussed in xref:jmx.adoc#jmx-mbean-shutdown[Orderly Shutdown Managed Operation], this operation can be invoked by using JMX.
If you wish to programmatically invoke the method, you need to inject or otherwise get a reference to the `IntegrationMBeanExporter`.
If no `id` attribute is provided on the `<int-jmx:mbean-export/>` definition, the bean has a generated name.
This name contains a random component to avoid `ObjectName` collisions if multiple Spring Integration contexts exist in the same JVM (`MBeanServer`).

For this reason, if you wish to invoke the method programmatically, we recommend that you provide the exporter with an `id` attribute so that you can easily access it in the application context.

Finally, the operation can be invoked by using the `<control-bus>` element.
See the https://github.com/spring-projects/spring-integration-samples/tree/main/intermediate/monitoring[monitoring Spring Integration sample application] for details.

NOTE: The algorithm described earlier was improved in version 4.1.
Previously, all task executors and schedulers were stopped.
This could cause mid-flow messages in `QueueChannel` instances to remain.
Now the shutdown leaves pollers running, to let these messages be drained and processed.
