This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new c0040cb56c9e CAMEL-27043: camel-paho-mqtt5 - manualAcksEnabled: the 
reconnect after a failed message connects a new client, as a connect of the 
same client hangs while another message is still in a synchronous route (#30921)
c0040cb56c9e is described below

commit c0040cb56c9ec2f440bd4c8b9b5164d92590a379
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 20:26:01 2026 +0530

    CAMEL-27043: camel-paho-mqtt5 - manualAcksEnabled: the reconnect after a 
failed message connects a new client, as a connect of the same client hangs 
while another message is still in a synchronous route (#30921)
    
    With manualAcksEnabled, QoS 1 and a persistent session, a failed exchange 
makes the
    consumer disconnect and connect its own client again (CAMEL-25793). With a
    synchronous route the exchange runs on the Paho callback thread, and when 
another
    message was still in the route that connect never completed: Paho 1.2.5 
does not wait
    for the old callback thread, and the next connect of the same client waits 
forever.
    On Artemis the consumer then ended up connected with no deliveries.
    
    The reconnect now closes the client and connects a new client with the same 
client
    id, which resumes the session with its own threads. A lock orders the 
replacement
    against the stop and against acknowledgements, so no acknowledgement goes 
to a closed
    client and no left-over client takes the session (CAMEL-27041). Exchanges 
still in
    the route on the closed client are not acknowledged, so the broker 
redelivers them.
    A failed connect or creation of the new client is retried with the backoff.
    getClient() returns the new instance afterwards; the component page and the 
4.24
    upgrade guide say so.
    
    New PahoMqtt5ConsumerReconnectWhileRoutingTest (real client, embedded 
Artemis) and
    PahoMqtt5ConsumerReconnectNewClientTest (mocked clients).
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/paho-mqtt5-component.adoc   |   9 +-
 .../src/main/docs/paho-mqtt5-component.adoc        |   9 +-
 .../paho/mqtt5/PahoMqtt5ClientCallback.java        |   8 +-
 .../component/paho/mqtt5/PahoMqtt5Consumer.java    | 256 ++++++++++++-----
 .../PahoMqtt5ConsumerReconnectNewClientTest.java   | 320 +++++++++++++++++++++
 ...PahoMqtt5ConsumerReconnectWhileRoutingTest.java | 154 ++++++++++
 .../paho/mqtt5/PahoMqtt5SubscribeRefusedTest.java  |   6 +-
 .../camel/component/paho/mqtt5/dst/FakeMqtt.java   |   6 +-
 .../component/paho/mqtt5/dst/PahoMqtt5World.java   |  14 +-
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |   4 +-
 10 files changed, 690 insertions(+), 96 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/paho-mqtt5-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/paho-mqtt5-component.adoc
index 58119b329ad5..401608a1eea3 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/paho-mqtt5-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/paho-mqtt5-component.adoc
@@ -102,9 +102,12 @@ The reconnects of failed exchanges in a row back off: the 
first one waits one se
 long, up to `maxReconnectDelay` (but at least one second), and any exchange 
that succeeds, also one of another
 message, starts again from one second. So on a topic where other messages 
succeed in between, a message that always
 fails makes the consumer reconnect about once a second.
-Each such reconnect is logged at WARN. The broker then also sends again the 
other QoS 1 messages that were not
-acknowledged yet, such as the ones still being routed. A message that always 
fails is still delivered again and again;
-use a Camel error handler, for example a dead letter channel, for such 
messages.
+Each such reconnect is logged at WARN. The consumer closes its client and 
connects a new one with the same client id,
+which resumes the session, so `getClient()` of the consumer returns another 
instance afterwards. The broker then also
+sends again the other QoS 1 messages that were not acknowledged yet, such as 
the ones still being routed: those are
+not acknowledged when their exchange completes, as their client is closed, so 
such a message is routed twice, the
+second time possibly while its first exchange is still running. A message that 
always fails is still delivered again
+and again; use a Camel error handler, for example a dead letter channel, for 
such messages.
 
 
 == Examples
diff --git 
a/components/camel-paho-mqtt5/src/main/docs/paho-mqtt5-component.adoc 
b/components/camel-paho-mqtt5/src/main/docs/paho-mqtt5-component.adoc
index 58119b329ad5..401608a1eea3 100644
--- a/components/camel-paho-mqtt5/src/main/docs/paho-mqtt5-component.adoc
+++ b/components/camel-paho-mqtt5/src/main/docs/paho-mqtt5-component.adoc
@@ -102,9 +102,12 @@ The reconnects of failed exchanges in a row back off: the 
first one waits one se
 long, up to `maxReconnectDelay` (but at least one second), and any exchange 
that succeeds, also one of another
 message, starts again from one second. So on a topic where other messages 
succeed in between, a message that always
 fails makes the consumer reconnect about once a second.
-Each such reconnect is logged at WARN. The broker then also sends again the 
other QoS 1 messages that were not
-acknowledged yet, such as the ones still being routed. A message that always 
fails is still delivered again and again;
-use a Camel error handler, for example a dead letter channel, for such 
messages.
+Each such reconnect is logged at WARN. The consumer closes its client and 
connects a new one with the same client id,
+which resumes the session, so `getClient()` of the consumer returns another 
instance afterwards. The broker then also
+sends again the other QoS 1 messages that were not acknowledged yet, such as 
the ones still being routed: those are
+not acknowledged when their exchange completes, as their client is closed, so 
such a message is routed twice, the
+second time possibly while its first exchange is still running. A message that 
always fails is still delivered again
+and again; use a Camel error handler, for example a dead letter channel, for 
such messages.
 
 
 == Examples
diff --git 
a/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ClientCallback.java
 
b/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ClientCallback.java
index 5265e026aa81..d3026074413f 100644
--- 
a/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ClientCallback.java
+++ 
b/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ClientCallback.java
@@ -126,7 +126,7 @@ final class PahoMqtt5ClientCallback implements MqttCallback 
{
         PahoMqtt5Consumer[] current = consumers.toArray(new 
PahoMqtt5Consumer[0]);
         if (ownedClient && current.length == 1) {
             // the own client of a consumer: it is the only one that 
subscribed, so it gets every message, as before
-            current[0].onMessageArrived(topic, message);
+            current[0].onMessageArrived(client, topic, message);
             return;
         }
         // a shared client: a stopped consumer can leave its subscription on 
the client (cleanStart / cleanSession
@@ -134,7 +134,7 @@ final class PahoMqtt5ClientCallback implements MqttCallback 
{
         boolean delivered = false;
         for (PahoMqtt5Consumer consumer : current) {
             if (matches(consumer.getEndpoint().getTopic(), topic)) {
-                consumer.onMessageArrived(topic, message);
+                consumer.onMessageArrived(client, topic, message);
                 delivered = true;
             }
         }
@@ -142,8 +142,8 @@ final class PahoMqtt5ClientCallback implements MqttCallback 
{
             // with manual acks the client sends no PUBACK for a QoS 1 message 
until it is acknowledged, and the broker
             // sends no more than receiveMaximum unacknowledged messages, so a 
dropped message that stays unacknowledged
             // would stop every consumer of the client; the client completes 
the QoS 2 flow on its own
-            // (the own client of a consumer is not acknowledged: it is being 
stopped, and a session that the broker
-            // keeps sends the message again on the next connect)
+            // (the own client of a consumer is not acknowledged: it is being 
stopped, or replaced after a failed
+            // exchange, and a session that the broker keeps sends the message 
again on the next connect)
             boolean acknowledge = !ownedClient && manualAcks && 
message.getQos() == 1;
             String dropped = acknowledge ? "dropped and acknowledged" : 
"dropped";
             if (warnedTopics.size() < MAX_WARNED_TOPICS && 
warnedTopics.add(topic)) {
diff --git 
a/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5Consumer.java
 
b/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5Consumer.java
index e16f446ae676..e87657fb3334 100644
--- 
a/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5Consumer.java
+++ 
b/components/camel-paho-mqtt5/src/main/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5Consumer.java
@@ -48,10 +48,11 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
     private volatile MqttConnectionOptions connectionOptions;
     private final AtomicBoolean restarting = new AtomicBoolean(false);
     private final AtomicBoolean reconnecting = new AtomicBoolean(false);
-    // set while the consumer connects the client again after a failed 
exchange: Paho reports that connect to
-    // connectComplete with reconnect=true once the client lost a connection 
on its own (it never clears its
-    // reconnecting flag), and the consumer subscribes again there only for 
the automatic reconnects of Paho
-    private final AtomicBoolean ownReconnect = new AtomicBoolean(false);
+    // guards the replacement of the client by a reconnect, the client = null 
of a stop, and the acknowledgement of an
+    // exchange: an exchange is never acknowledged on a client that the 
consumer closed
+    private final Object clientLock = new Object();
+    // the client that a reconnect closes, until the reconnect replaced it: 
its exchanges are no longer acknowledged
+    private MqttClient replacedClient;
     // failed exchanges in a row that made the consumer reconnect, for the 
backoff; reset by a successful exchange
     private final AtomicInteger failedMessageReconnects = new AtomicInteger();
     private volatile ScheduledExecutorService reconnectExecutor;
@@ -60,6 +61,11 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
         super(endpoint, processor);
     }
 
+    /**
+     * The client of the consumer. With manualAcksEnabled on a session that 
the broker keeps, a failed exchange makes
+     * the consumer replace its own client with a new one (see {@link 
#reconnect(MqttClient)}), so this can return
+     * another instance afterwards.
+     */
     public MqttClient getClient() {
         return client;
     }
@@ -89,10 +95,7 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
                 if (clientId == null) {
                     clientId = PahoMqtt5Endpoint.generateClientId();
                 }
-                client = createClient();
-                if (getEndpoint().getConfiguration().isManualAcksEnabled()) {
-                    client.setManualAcks(true);
-                }
+                client = createOwnClient();
             }
 
             // the client can be shared by the consumers of several endpoints, 
and it has a single callback
@@ -155,11 +158,14 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
 
     @Override
     protected void doStop() throws Exception {
-        MqttClient ownedClient = stopClient ? client : null;
+        MqttClient ownedClient;
+        synchronized (clientLock) {
+            // isRunAllowed() is false by now, so a reconnect no longer 
replaces the client
+            ownedClient = stopClient ? client : null;
+        }
         Exception stopException = null;
         shutdownReconnectExecutor();
         reconnecting.set(false);
-        ownReconnect.set(false);
         try {
             super.doStop();
 
@@ -192,9 +198,12 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
             stopException = e;
         } finally {
             PahoMqtt5ClientCallback.unregister(this);
-            if (ownedClient != null) {
-                // an externally provided client is kept, so that the consumer 
uses it again when it starts again
-                client = null;
+            synchronized (clientLock) {
+                if (ownedClient != null) {
+                    // an externally provided client is kept, so that the 
consumer uses it again when it starts again
+                    client = null;
+                }
+                replacedClient = null;
             }
             stopClient = false;
             if (ownedClient != null) {
@@ -225,12 +234,12 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
     }
 
     /**
-     * The client connected again: subscribes again after a reconnect of the 
client, but not after the connect of
-     * {@link #reconnect(MqttClient)}, which subscribes again itself, only 
when the broker did not keep the session.
+     * The client connected: subscribes again after an automatic reconnect of 
Paho. The first connect of a client is not
+     * a reconnect, also the connect of the new client of {@link 
#reconnect(MqttClient)}, which subscribes itself, only
+     * when the broker did not keep the session.
      */
     void connectComplete(boolean reconnect) {
-        boolean own = ownReconnect.compareAndSet(true, false);
-        if (reconnect && !own) {
+        if (reconnect) {
             resubscribe();
         }
     }
@@ -279,14 +288,32 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
         }
     }
 
-    void onMessageArrived(String topic, MqttMessage message) {
-        Exchange exchange = createExchange(message, topic);
+    /**
+     * Routes a message of the client callback.
+     *
+     * @param receivingClient the client the message arrived on, which the 
callback passes in: a reconnect after a
+     *                        failed exchange can replace the client of the 
consumer while this message is on its way to
+     *                        the route, and its packet id is only valid on 
the client it arrived on
+     */
+    void onMessageArrived(MqttClient receivingClient, String topic, 
MqttMessage message) {
+        Exchange exchange = createExchange(message, topic, receivingClient);
 
         // use default consumer callback
         AsyncCallback cb = defaultConsumerCallback(exchange, true);
         getAsyncProcessor().process(exchange, cb);
     }
 
+    /**
+     * Creates the own client of the consumer, for a start and for a reconnect 
after a failed exchange.
+     */
+    private MqttClient createOwnClient() throws MqttException {
+        MqttClient ownClient = createClient();
+        if (getEndpoint().getConfiguration().isManualAcksEnabled()) {
+            ownClient.setManualAcks(true);
+        }
+        return ownClient;
+    }
+
     MqttClient createClient() throws MqttException {
         return new MqttClient(
                 getEndpoint().getConfiguration().getBrokerUrl(),
@@ -361,28 +388,42 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
      * it is acknowledged, which frees its place in the receive window.
      */
     private void rollback(Exchange exchange, MqttMessage mqttMessage, 
MqttClient receivingClient) {
-        MqttClient current = client;
-        if (current == null || current != receivingClient) {
-            logNotAcknowledgedAfterStop(exchange, mqttMessage);
-            return;
-        }
-        if (mqttMessage.getQos() != 1 || !isSessionKeptAfterDisconnect()) {
-            LOG.debug("Acknowledging failed MQTT message with ID: {} (QoS {}) 
of Exchange ID: {} as the broker does not"
-                      + " deliver it again",
-                    mqttMessage.getId(), mqttMessage.getQos(), 
exchange.getExchangeId());
-            try {
-                current.messageArrivedComplete(mqttMessage.getId(), 
mqttMessage.getQos());
-            } catch (MqttException e) {
-                getExceptionHandler().handleException(
-                        "Error acknowledging failed MQTT message with ID: " + 
mqttMessage.getId(), exchange, e);
+        MqttException ackException = null;
+        synchronized (clientLock) {
+            if (!isCurrentClient(receivingClient)) {
+                logNotAcknowledgedAfterStop(exchange, mqttMessage);
+                return;
+            }
+            if (mqttMessage.getQos() != 1 || !isSessionKeptAfterDisconnect()) {
+                LOG.debug("Acknowledging failed MQTT message with ID: {} (QoS 
{}) of Exchange ID: {} as the broker does"
+                          + " not deliver it again",
+                        mqttMessage.getId(), mqttMessage.getQos(), 
exchange.getExchangeId());
+                try {
+                    
receivingClient.messageArrivedComplete(mqttMessage.getId(), 
mqttMessage.getQos());
+                } catch (MqttException e) {
+                    ackException = e;
+                }
+            } else if (stopClient) {
+                // under the lock, so that the reconnect is scheduled for the 
client that is still the current one
+                reconnectAfterFailure(receivingClient, exchange, mqttMessage);
+            } else {
+                LOG.warn("Rollback due to error processing Exchange ID: {}: 
MQTT message with ID: {} stays unacknowledged"
+                         + " until the externally provided client connects 
again",
+                        exchange.getExchangeId(), mqttMessage.getId());
             }
-        } else if (stopClient) {
-            reconnectAfterFailure(current, exchange, mqttMessage);
-        } else {
-            LOG.warn("Rollback due to error processing Exchange ID: {}: MQTT 
message with ID: {} stays unacknowledged"
-                     + " until the externally provided client connects again",
-                    exchange.getExchangeId(), mqttMessage.getId());
         }
+        if (ackException != null) {
+            getExceptionHandler().handleException(
+                    "Error acknowledging failed MQTT message with ID: " + 
mqttMessage.getId(), exchange, ackException);
+        }
+    }
+
+    /**
+     * Whether an exchange of the given client is acknowledged: the client is 
the current one, and a reconnect is not
+     * closing it. Called with the clientLock held.
+     */
+    private boolean isCurrentClient(MqttClient receivingClient) {
+        return receivingClient != null && receivingClient == client && 
receivingClient != replacedClient;
     }
 
     private void reconnectAfterFailure(MqttClient current, Exchange exchange, 
MqttMessage mqttMessage) {
@@ -406,37 +447,95 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
         return Math.max(min, Math.min(delay, max));
     }
 
+    /**
+     * Reconnects after a failed exchange, so that the broker sends the 
unacknowledged messages of the session again.
+     * <p>
+     * The consumer does not connect the same client again: it disconnects and 
closes it, and connects a new client with
+     * the same client id, which resumes the session that the broker kept. 
Paho 1.2.5 starts the threads of a new
+     * connection of a client (CommsCallback, CommsSender) only once the 
threads of its previous connection have ended,
+     * and otherwise waits for them forever, with no timeout. With a 
synchronous route the exchange runs on the callback
+     * thread of Paho, so that thread is still busy when another message is in 
the route, and a connect of the same
+     * client hung there (CAMEL-27043). The exchanges still in the route on 
the closed client are not acknowledged: the
+     * broker sends them again to the new client.
+     */
     private void reconnect(MqttClient current) {
+        if (!isRunAllowed() || current != client) {
+            // the consumer stopped, or started again with another client
+            return;
+        }
         try {
             // the message callback may still be running (disconnect is not 
allowed from it), so this runs here
-            if (isRunAllowed() && current == client && current.isConnected()) {
+            if (current.isConnected()) {
                 current.disconnect();
             }
         } catch (Exception e) {
             getExceptionHandler().handleException("Failed to disconnect after 
a failed exchange", e);
         }
-        // the disconnect covers every message that failed until now; a 
message the broker sends again on the new
-        // connection can fail before this method returns, and must be able to 
schedule the next reconnect
-        reconnecting.set(false);
+        synchronized (clientLock) {
+            // from now on its exchanges are not acknowledged: the client is 
closed next (an acknowledgement on a closed
+            // client fails in Paho), and the broker sends them again to the 
new client
+            replacedClient = current;
+        }
+        Exception closeException = closeOwnedClient(current, null);
+        if (closeException != null) {
+            getExceptionHandler().handleException("Failed to close the client 
after a failed exchange", closeException);
+        }
+        MqttClient next = null;
+        boolean replaced = false;
         try {
-            if (isRunAllowed() && current == client && !current.isConnected()) 
{
-                ownReconnect.set(true);
-                IMqttToken token = 
current.connectWithResult(connectionOptions);
-                // the subscription is part of the session; subscribing again 
would make the broker send the retained
-                // message of the topic again (Retain Handling 0)
-                if (!token.getSessionPresent()) {
-                    LOG.warn("The broker did not keep the session of client: 
{}: the failed MQTT message and the other"
-                             + " unacknowledged ones are not delivered again; 
subscribing again to topic: {}",
-                            clientId, getEndpoint().getTopic());
-                    subscribeAfterReconnect(current);
+            // after the close: with file persistence both clients use the 
directory of the client id, and Paho 1.2.5
+            // goes on when another client holds its lock, so the old client 
is done with it first
+            next = createOwnClient();
+            synchronized (clientLock) {
+                // the stop reads the client under the same lock once 
isRunAllowed() is false, so either it closes the
+                // new client, or the new client is not used
+                if (isRunAllowed() && current == client) {
+                    client = next;
+                    replacedClient = null;
+                    PahoMqtt5ClientCallback.unregister(this);
+                    // the callback is set before the connect: the broker 
sends the messages of the session right after
+                    // CONNACK
+                    PahoMqtt5ClientCallback.register(next, this, true);
+                    // a message that the broker sends again on the new 
connection can fail before this method returns,
+                    // and must be able to schedule the next reconnect
+                    reconnecting.set(false);
+                    replaced = true;
+                } else if (replacedClient == current) {
+                    replacedClient = null;
+                }
+            }
+            if (!replaced) {
+                LOG.debug("The consumer of client: {} stopped while it 
reconnected: the new client is closed", clientId);
+                Exception closeFailure = closeOwnedClient(next, null);
+                if (closeFailure != null) {
+                    LOG.debug("Client: {} could not be closed: {}", clientId, 
closeFailure.getMessage(), closeFailure);
                 }
+                return;
+            }
+            LOG.debug("Connecting a new client: {} to broker: {} after a 
failed exchange", clientId,
+                    getEndpoint().getConfiguration().getBrokerUrl());
+            IMqttToken token = next.connectWithResult(connectionOptions);
+            // the subscription is part of the session; subscribing again 
would make the broker send the retained
+            // message of the topic again (Retain Handling 0)
+            if (!token.getSessionPresent()) {
+                LOG.warn("The broker did not keep the session of client: {}: 
the failed MQTT message and the other"
+                         + " unacknowledged ones are not delivered again; 
subscribing again to topic: {}",
+                        clientId, getEndpoint().getTopic());
+                subscribeAfterReconnect(next);
             }
         } catch (Exception e) {
-            // a failed connect does not call connectComplete
-            ownReconnect.set(false);
             getExceptionHandler().handleException("Failed to reconnect after a 
failed exchange", e);
             // the client does not reconnect on its own after a disconnect it 
was asked for, so try again later
-            scheduleReconnect(current, "Reconnect failed");
+            synchronized (clientLock) {
+                MqttClient retry = replaced ? next : current;
+                if (!replaced) {
+                    // no new client: this reconnect is still the one pending
+                    reconnecting.set(false);
+                }
+                if (retry == client) {
+                    scheduleReconnect(retry, "Reconnect failed");
+                }
+            }
         }
     }
 
@@ -488,7 +587,14 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
         return (PahoMqtt5Endpoint) super.getEndpoint();
     }
 
+    /**
+     * Creates the exchange of a message that arrived on the current client of 
the consumer.
+     */
     public Exchange createExchange(MqttMessage mqttMessage, String topic) {
+        return createExchange(mqttMessage, topic, client);
+    }
+
+    private Exchange createExchange(MqttMessage mqttMessage, String topic, 
MqttClient receivingClient) {
         Exchange exchange = createExchange(true);
 
         PahoMqtt5Message paho = new PahoMqtt5Message(exchange.getContext(), 
mqttMessage);
@@ -499,25 +605,29 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
 
         exchange.setIn(paho);
         if (getEndpoint().getConfiguration().isManualAcksEnabled()) {
-            // the message is acknowledged on the client it arrived on: once 
the consumer stopped, that client is closed
-            // (or replaced by the client of the next start), and its packet 
id means nothing to another client
-            MqttClient receivingClient = client;
+            // the message is acknowledged on the client it arrived on: once 
the consumer stopped or reconnected after a
+            // failed exchange, that client is closed (and replaced by a new 
client), and its packet id means nothing to
+            // another client
             exchange.getExchangeExtension().addOnCompletion(new 
SynchronizationAdapter() {
                 @Override
                 public void onComplete(Exchange exchange) {
-                    MqttClient current = client;
-                    if (current == null || current != receivingClient) {
-                        // not a message of the current client: its backoff is 
left as is
-                        logNotAcknowledgedAfterStop(exchange, mqttMessage);
-                        return;
+                    MqttException ackException = null;
+                    synchronized (clientLock) {
+                        if (!isCurrentClient(receivingClient)) {
+                            // not a message of the current client: its 
backoff is left as is
+                            logNotAcknowledgedAfterStop(exchange, mqttMessage);
+                            return;
+                        }
+                        failedMessageReconnects.set(0);
+                        try {
+                            
receivingClient.messageArrivedComplete(mqttMessage.getId(), 
mqttMessage.getQos());
+                        } catch (MqttException e) {
+                            ackException = e;
+                        }
                     }
-                    failedMessageReconnects.set(0);
-                    try {
-                        current.messageArrivedComplete(mqttMessage.getId(), 
mqttMessage.getQos());
-                    } catch (MqttException e) {
+                    if (ackException != null) {
                         getExceptionHandler().handleException(
-                                "Error acknowledging MQTT message with ID: " + 
mqttMessage.getId(),
-                                exchange, e);
+                                "Error acknowledging MQTT message with ID: " + 
mqttMessage.getId(), exchange, ackException);
                     }
                 }
 
@@ -531,9 +641,9 @@ public class PahoMqtt5Consumer extends DefaultConsumer {
     }
 
     private void logNotAcknowledgedAfterStop(Exchange exchange, MqttMessage 
mqttMessage) {
-        LOG.debug("MQTT message with ID: {} of Exchange ID: {} is not 
acknowledged: the consumer stopped and closed the client"
-                  + " it arrived on (on a session that the broker keeps, the 
broker sends it again to a client with the"
-                  + " same client id)",
+        LOG.debug("MQTT message with ID: {} of Exchange ID: {} is not 
acknowledged: the consumer stopped or reconnected, and"
+                  + " closed the client it arrived on (on a session that the 
broker keeps, the broker sends it again to a"
+                  + " client with the same client id)",
                 mqttMessage.getId(), exchange.getExchangeId());
     }
 
diff --git 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ConsumerReconnectNewClientTest.java
 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ConsumerReconnectNewClientTest.java
new file mode 100644
index 000000000000..f00de7bfc093
--- /dev/null
+++ 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ConsumerReconnectNewClientTest.java
@@ -0,0 +1,320 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.paho.mqtt5;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.Synchronization;
+import org.apache.camel.support.service.ServiceHelper;
+import org.eclipse.paho.mqttv5.client.IMqttToken;
+import org.eclipse.paho.mqttv5.client.MqttCallback;
+import org.eclipse.paho.mqttv5.client.MqttClient;
+import org.eclipse.paho.mqttv5.client.MqttClientException;
+import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
+import org.eclipse.paho.mqttv5.common.MqttException;
+import org.eclipse.paho.mqttv5.common.MqttMessage;
+import org.eclipse.paho.mqttv5.common.MqttPersistenceException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * manualAcksEnabled on a session that the broker keeps: a failed QoS 1 
exchange makes the consumer reconnect with a new
+ * client, as Paho 1.2.5 may never complete a connect of the same client while 
its callback thread still routes a
+ * message (CAMEL-27043). The clients are mocks; 
PahoMqtt5ConsumerReconnectWhileRoutingTest runs the real client against
+ * a broker.
+ */
+class PahoMqtt5ConsumerReconnectNewClientTest {
+
+    private final Deque<Object> clients = new ArrayDeque<>();
+    private final List<String> events = new CopyOnWriteArrayList<>();
+    // the exchanges that reached the route
+    private final List<Exchange> routed = new CopyOnWriteArrayList<>();
+    // runs once when the callback hands the next message to the consumer, 
before the consumer creates its exchange
+    private volatile Runnable beforeExchange;
+    private CamelContext context;
+    private PahoMqtt5Consumer consumer;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        context = new DefaultCamelContext();
+        context.start();
+        PahoMqtt5Configuration configuration = new PahoMqtt5Configuration();
+        configuration.setQos(1);
+        configuration.setManualAcksEnabled(true);
+        configuration.setCleanStart(false);
+        configuration.setSessionExpiryInterval(60);
+        PahoMqtt5Endpoint endpoint = new PahoMqtt5Endpoint(
+                "paho-mqtt5:test", "test", context.getComponent("paho-mqtt5", 
PahoMqtt5Component.class), configuration);
+        consumer = new PahoMqtt5Consumer(endpoint, routed::add) {
+            @Override
+            void onMessageArrived(MqttClient receivingClient, String topic, 
MqttMessage message) {
+                Runnable hook = beforeExchange;
+                beforeExchange = null;
+                if (hook != null) {
+                    hook.run();
+                }
+                super.onMessageArrived(receivingClient, topic, message);
+            }
+
+            @Override
+            MqttClient createClient() throws MqttException {
+                events.add("create");
+                Object next = clients.removeFirst();
+                if (next instanceof MqttException e) {
+                    throw e;
+                }
+                if (next instanceof CountDownLatch[] latches) {
+                    // [0] counted down once the reconnect creates the client, 
[1] lets it go on
+                    latches[0].countDown();
+                    awaitIgnoringInterrupts(latches[1]);
+                    return (MqttClient) clients.removeFirst();
+                }
+                return (MqttClient) next;
+            }
+        };
+    }
+
+    @AfterEach
+    void tearDown() {
+        // leaves no entry of the consumer in the static callbacks of the 
clients
+        ServiceHelper.stopService(consumer);
+        context.stop();
+    }
+
+    @Test
+    void failedExchangeClosesTheClientAndConnectsANewOne() throws Exception {
+        MqttClient first = addClient("1");
+        MqttClient second = addClient("2");
+        consumer.start();
+
+        fail(consumer.createExchange(message(7), "test"));
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> consumer.getClient() 
== second && events.contains("connect 2"));
+        // the first client is closed before the second one is created (with 
file persistence both use the directory of
+        // the client id), and the callback is set before the connect
+        assertThat(events).containsExactly("create", "connect 1", "disconnect 
1", "close 1", "create", "connect 2");
+        verify(second).setManualAcks(true);
+        verify(second).setCallback(any(MqttCallback.class));
+        verify(first, 
never()).connectWithResult(any(MqttConnectionOptions.class));
+        assertThat(consumer.getFailedMessageReconnects()).isOne();
+    }
+
+    @Test
+    void exchangeOfTheReplacedClientIsNotAcknowledged() throws Exception {
+        MqttClient first = addClient("1");
+        MqttClient second = addClient("2");
+        consumer.start();
+        Exchange inRoute = consumer.createExchange(message(8), "test");
+
+        fail(consumer.createExchange(message(7), "test"));
+        await().atMost(10, TimeUnit.SECONDS).until(() -> consumer.getClient() 
== second && events.contains("connect 2"));
+        complete(inRoute);
+
+        // not on the closed client, and packet id 8 of the closed connection 
is not a message of the new client; the
+        // broker sends the message again to the new client
+        verify(first, never()).messageArrivedComplete(anyInt(), anyInt());
+        verify(second, never()).messageArrivedComplete(anyInt(), anyInt());
+        assertThat(consumer.getFailedMessageReconnects()).isOne();
+
+        complete(consumer.createExchange(message(9), "test"));
+        verify(second).messageArrivedComplete(9, 1);
+        assertThat(consumer.getFailedMessageReconnects()).isZero();
+    }
+
+    @Test
+    void messageTakenBeforeTheClientIsReplacedKeepsTheClientItArrivedOn() 
throws Exception {
+        MqttClient first = addClient("1");
+        MqttClient second = addClient("2");
+        consumer.start();
+        ArgumentCaptor<MqttCallback> firstCallback = 
ArgumentCaptor.forClass(MqttCallback.class);
+        verify(first).setCallback(firstCallback.capture());
+        // the callback thread of the first client has taken message 8 and 
handed it to the consumer, and another
+        // exchange fails and replaces the client before the consumer creates 
the exchange of message 8
+        beforeExchange = () -> {
+            fail(consumer.createExchange(message(7), "test"));
+            await().atMost(10, TimeUnit.SECONDS)
+                    .until(() -> consumer.getClient() == second && 
events.contains("connect 2"));
+        };
+
+        firstCallback.getValue().messageArrived("test", message(8));
+        assertThat(routed).hasSize(1);
+        complete(routed.get(0));
+
+        // packet id 8 belongs to the closed connection of the first client: 
acknowledging it on the second client
+        // would acknowledge the copy that the broker sends again on the 
resumed session
+        verify(first, never()).messageArrivedComplete(anyInt(), anyInt());
+        verify(second, never()).messageArrivedComplete(anyInt(), anyInt());
+        assertThat(consumer.getFailedMessageReconnects()).isOne();
+    }
+
+    @Test
+    void failedExchangeOfTheReplacedClientDoesNotReconnect() throws Exception {
+        addClient("1");
+        MqttClient second = addClient("2");
+        consumer.start();
+        Exchange inRoute = consumer.createExchange(message(8), "test");
+
+        fail(consumer.createExchange(message(7), "test"));
+        await().atMost(10, TimeUnit.SECONDS).until(() -> consumer.getClient() 
== second && events.contains("connect 2"));
+        fail(inRoute);
+
+        // scheduleReconnect counts the reconnects in a row at once
+        assertThat(consumer.getFailedMessageReconnects()).isOne();
+        verify(second, never()).disconnect();
+    }
+
+    @Test
+    void stopWhileTheNewClientIsCreatedClosesIt() throws Exception {
+        addClient("1");
+        CountDownLatch creating = new CountDownLatch(1);
+        CountDownLatch release = new CountDownLatch(1);
+        clients.add(new CountDownLatch[] { creating, release });
+        MqttClient second = addClient("2");
+        consumer.start();
+
+        fail(consumer.createExchange(message(7), "test"));
+        assertThat(creating.await(10, TimeUnit.SECONDS)).isTrue();
+        consumer.stop();
+        release.countDown();
+
+        // the stopped consumer neither uses nor connects the new client
+        await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> 
verify(second).close(true));
+        verify(second, 
never()).connectWithResult(any(MqttConnectionOptions.class));
+        assertThat(consumer.getClient()).isNull();
+    }
+
+    @Test
+    void failedCreateOfTheNewClientIsRetried() throws Exception {
+        addClient("1");
+        // what the constructor of a client throws when the file persistence 
directory cannot be written (Paho 1.2.5
+        // ignores a lock that another client holds)
+        clients.add(new MqttPersistenceException());
+        MqttClient second = addClient("2");
+        consumer.start();
+
+        fail(consumer.createExchange(message(7), "test"));
+
+        // the second reconnect waits 2 seconds
+        await().atMost(10, TimeUnit.SECONDS).until(() -> consumer.getClient() 
== second && events.contains("connect 2"));
+        assertThat(consumer.getFailedMessageReconnects()).isEqualTo(2);
+    }
+
+    @Test
+    void failedConnectOfTheNewClientIsRetriedWithAnotherClient() throws 
Exception {
+        addClient("1");
+        MqttClient second = addClient("2");
+        doThrow(new 
MqttException(MqttClientException.REASON_CODE_SERVER_CONNECT_ERROR)).when(second)
+                .connectWithResult(any(MqttConnectionOptions.class));
+        MqttClient third = addClient("3");
+        consumer.start();
+
+        fail(consumer.createExchange(message(7), "test"));
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> consumer.getClient() 
== third && events.contains("connect 3"));
+        assertThat(events).containsSubsequence("close 1", "create", "close 2", 
"create", "connect 3");
+        assertThat(consumer.getFailedMessageReconnects()).isEqualTo(2);
+    }
+
+    /**
+     * A mock client that is connected after connect or connectWithResult and 
disconnected after disconnect, and records
+     * those calls and close(true) in {@link #events}.
+     */
+    private MqttClient addClient(String name) throws Exception {
+        MqttClient client = mock(MqttClient.class);
+        AtomicBoolean connected = new AtomicBoolean();
+        when(client.isConnected()).thenAnswer(invocation -> connected.get());
+        doAnswer(invocation -> {
+            events.add("connect " + name);
+            connected.set(true);
+            return null;
+        }).when(client).connect(any(MqttConnectionOptions.class));
+        IMqttToken sessionPresent = mock(IMqttToken.class);
+        when(sessionPresent.getSessionPresent()).thenReturn(true);
+        
when(client.connectWithResult(any(MqttConnectionOptions.class))).thenAnswer(invocation
 -> {
+            events.add("connect " + name);
+            connected.set(true);
+            return sessionPresent;
+        });
+        doAnswer(invocation -> {
+            events.add("disconnect " + name);
+            connected.set(false);
+            return null;
+        }).when(client).disconnect();
+        doAnswer(invocation -> {
+            events.add("close " + name);
+            return null;
+        }).when(client).close(true);
+        clients.add(client);
+        return client;
+    }
+
+    private static void awaitIgnoringInterrupts(CountDownLatch latch) {
+        // the stop interrupts the reconnect thread (shutdownNow of its 
executor)
+        boolean interrupted = false;
+        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
+        while (latch.getCount() > 0 && System.nanoTime() < deadline) {
+            try {
+                latch.await(1, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                interrupted = true;
+            }
+        }
+        if (interrupted) {
+            Thread.currentThread().interrupt();
+        }
+    }
+
+    private static MqttMessage message(int id) {
+        MqttMessage message = new MqttMessage("body".getBytes());
+        message.setId(id);
+        message.setQos(1);
+        return message;
+    }
+
+    private static void complete(Exchange exchange) {
+        List<Synchronization> completions = 
exchange.getExchangeExtension().handoverCompletions();
+        completions.forEach(completion -> completion.onComplete(exchange));
+    }
+
+    private static void fail(Exchange exchange) {
+        exchange.setException(new IllegalStateException("failed"));
+        List<Synchronization> completions = 
exchange.getExchangeExtension().handoverCompletions();
+        completions.forEach(completion -> completion.onFailure(exchange));
+    }
+}
diff --git 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ConsumerReconnectWhileRoutingTest.java
 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ConsumerReconnectWhileRoutingTest.java
new file mode 100644
index 000000000000..18e46be6c14b
--- /dev/null
+++ 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5ConsumerReconnectWhileRoutingTest.java
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.paho.mqtt5;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.activemq.artemis.core.config.WildcardConfiguration;
+import org.apache.activemq.artemis.core.protocol.mqtt.MQTTUtil;
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.test.infra.artemis.services.ArtemisService;
+import org.apache.camel.test.infra.artemis.services.ArtemisServiceFactory;
+import org.eclipse.paho.mqttv5.client.MqttClient;
+import org.eclipse.paho.mqttv5.client.MqttClientException;
+import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
+import org.eclipse.paho.mqttv5.common.MqttException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * manualAcksEnabled on a session that the broker keeps, with a synchronous 
route: the exchange runs on the callback
+ * thread of Paho. A failed message makes the consumer reconnect while the 
next message is still in the route. Paho
+ * 1.2.5 starts the threads of a connection again only once the threads of the 
previous connection of the same client
+ * have ended, and waits for them forever otherwise, so a connect of the same 
client hung there (CAMEL-27043). A real
+ * Paho client against the embedded Artemis MQTT broker.
+ */
+@Timeout(60)
+class PahoMqtt5ConsumerReconnectWhileRoutingTest {
+
+    @RegisterExtension
+    static ArtemisService service = 
ArtemisServiceFactory.createSingletonMQTTService();
+
+    private final List<String> routed = new CopyOnWriteArrayList<>();
+    private final Map<String, AtomicInteger> attempts = new 
ConcurrentHashMap<>();
+    private final CountDownLatch slowInRoute = new CountDownLatch(1);
+    private final CountDownLatch releaseSlow = new CountDownLatch(1);
+
+    @Test
+    void reconnectWhileAMessageIsInTheRouteRoutesTheNextMessages() throws 
Exception {
+        String id = UUID.randomUUID().toString();
+        String clientId = "reconnect-routing-" + id;
+        String topic = "reconnect/routing/" + id;
+        String uri = "paho-mqtt5:" + topic + "?brokerUrl=" + brokerUrl()
+                     + 
"&qos=1&manualAcksEnabled=true&cleanStart=false&sessionExpiryInterval=60&clientId="
 + clientId;
+        CamelContext context = createContext(uri);
+        try {
+            PahoMqtt5Consumer consumer = (PahoMqtt5Consumer) 
context.getRoutes().get(0).getConsumer();
+            MqttClient first = consumer.getClient();
+
+            // fail-1 fails, so the consumer reconnects after 1 second, while 
slow-2 is still in the route
+            publish(topic, "fail-1", "slow-2");
+            assertThat(slowInRoute.await(10, TimeUnit.SECONDS)).isTrue();
+
+            // slow-2 stays in the route: the consumer connects again all the 
same, the broker sends fail-1 and slow-2
+            // again, and the consumer receives new messages
+            await().atMost(15, TimeUnit.SECONDS)
+                    .untilAsserted(() -> assertThat(routed).contains("fail-1", 
"slow-2"));
+            publish(topic, "after-3");
+            await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> 
assertThat(routed).contains("after-3"));
+            assertThat(consumer.getClient().isConnected()).isTrue();
+            // the client of the earlier connection is closed, so it cannot 
connect later and take the session over
+            assertThat(consumer.getClient()).isNotSameAs(first);
+            
assertThatThrownBy(first::connect).isInstanceOfSatisfying(MqttException.class,
+                    e -> 
assertThat(e.getReasonCode()).isEqualTo(MqttClientException.REASON_CODE_CLIENT_CLOSED));
+
+            // the first delivery of slow-2 leaves the route: it is not 
acknowledged (its connection is closed), and the
+            // consumer stays connected
+            releaseSlow.countDown();
+            await().atMost(10, TimeUnit.SECONDS)
+                    .untilAsserted(() -> 
assertThat(routed).containsExactlyInAnyOrder("fail-1", "slow-2", "after-3",
+                            "slow-2"));
+            assertThat(attempts.get("fail-1")).hasValue(2);
+            assertThat(attempts.get("after-3")).hasValue(1);
+            assertThat(consumer.getClient().isConnected()).isTrue();
+            // nothing is left unacknowledged at the broker
+            String queue = MQTTUtil.getCoreQueueFromMqttTopic(topic, clientId, 
new WildcardConfiguration());
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
service.countMessages(queue) == 0);
+            assertThat(consumer.getFailedMessageReconnects()).isZero();
+        } finally {
+            releaseSlow.countDown();
+            context.stop();
+        }
+    }
+
+    private CamelContext createContext(String uri) throws Exception {
+        CamelContext context = new DefaultCamelContext();
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(uri).process(exchange -> {
+                    String body = exchange.getMessage().getBody(String.class);
+                    int attempt = attempts.computeIfAbsent(body, b -> new 
AtomicInteger()).incrementAndGet();
+                    if (body.startsWith("fail") && attempt == 1) {
+                        throw new IllegalStateException("Forced failure of " + 
body);
+                    }
+                    if (body.startsWith("slow") && attempt == 1) {
+                        // a route step that takes longer than the reconnect 
delay (1 second), such as a slow call
+                        slowInRoute.countDown();
+                        releaseSlow.await(30, TimeUnit.SECONDS);
+                    }
+                    routed.add(body);
+                });
+            }
+        });
+        context.start();
+        return context;
+    }
+
+    private static void publish(String topic, String... bodies) throws 
Exception {
+        MqttClient publisher
+                = new MqttClient(brokerUrl(), "reconnect-routing-publisher-" + 
UUID.randomUUID(), new MemoryPersistence());
+        try {
+            publisher.connect();
+            for (String body : bodies) {
+                publisher.publish(topic, 
body.getBytes(StandardCharsets.UTF_8), 1, false);
+            }
+            publisher.disconnect();
+        } finally {
+            publisher.close();
+        }
+    }
+
+    private static String brokerUrl() {
+        return "tcp://localhost:" + service.brokerPort();
+    }
+}
diff --git 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5SubscribeRefusedTest.java
 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5SubscribeRefusedTest.java
index d82780e953c4..d462966d6c53 100644
--- 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5SubscribeRefusedTest.java
+++ 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5SubscribeRefusedTest.java
@@ -151,11 +151,11 @@ class PahoMqtt5SubscribeRefusedTest extends 
CamelTestSupport {
 
         callback.getValue().messageArrived("test", message);
 
-        // the reconnect subscribes again (refused), the stop of the restart 
closes the client, and so does the start
-        // that fails
+        // the reconnect closes the client and connects a new one (the same 
mock here), subscribes again (refused), the
+        // stop of the restart closes the client, and so does the start that 
fails
         await().atMost(10, TimeUnit.SECONDS)
                 .untilAsserted(() -> 
verify(client).connectWithResult(any(MqttConnectionOptions.class)));
-        await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> 
verify(client, times(2)).close(true));
+        await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> 
verify(client, times(3)).close(true));
         verify(client, times(3)).subscribe("test", 1);
         await().atMost(10, TimeUnit.SECONDS)
                 .untilAsserted(() -> 
assertThat(context.getRouteController().getRouteStatus(ROUTE_ID))
diff --git 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/FakeMqtt.java
 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/FakeMqtt.java
index 50e8532dc81f..b3fc66e935b7 100644
--- 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/FakeMqtt.java
+++ 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/FakeMqtt.java
@@ -68,8 +68,10 @@ import org.eclipse.paho.mqttv5.common.MqttMessage;
  * persistence of the client, the quiesce of a disconnect, the bound of 10 
messages of the queue of the callback thread,
  * the reconnect delay that Paho keeps for all clients of the JVM (each client 
has its own here), the order of
  * connectComplete and the messages resent at the connect (separate tasks 
here), the threads that Paho calls
- * connectComplete and disconnected on (tasks of the callback executor here), 
and a SUBACK that refuses a subscription
- * (the fake broker grants the QoS asked for, and the token reports it in 
getReasonCodes).
+ * connectComplete and disconnected on (tasks of the callback executor here), 
a callback thread per client (the clients
+ * share one callback executor here, so a new client delivers once a message 
of a closed client left the route; each
+ * client has its own callback state), and a SUBACK that refuses a 
subscription (the fake broker grants the QoS asked
+ * for, and the token reports it in getReasonCodes).
  * <p>
  * Timing (the one-stack rule of the harness): every call of the client takes 
a round trip and writes take effect at its
  * start; deliveries are tasks of the callback thread, one at a time, in order.
diff --git 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/PahoMqtt5World.java
 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/PahoMqtt5World.java
index 3b2ba319ddd2..ab229b8226e4 100644
--- 
a/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/PahoMqtt5World.java
+++ 
b/components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/dst/PahoMqtt5World.java
@@ -59,13 +59,13 @@ import org.apache.camel.test.dst.Invariants;
  * manual acknowledgements, or when the broker does not keep the session, its 
acknowledgement leaves it lost (the
  * consumer's Javadoc of rollback describes it), and the world does not count 
it.
  * <p>
- * One case is looked at separately. A connect that comes while the callback 
thread of Paho is still in messageArrived
- * after the connection closed (the reconnect of the consumer after a failed 
message, or the automatic reconnect, while
- * another message is in the route) never completes, as read in the byte code 
of Paho 1.2.5 (not reproduced against a
- * broker yet, and the fake leaves out the quiesce of a disconnect, which 
changes when the thread is busy): the client
- * stays connecting, the consumer delivers nothing more, and the stop cannot 
close the client. This is CAMEL-27043 (it
- * still needs a reproduction, and may be a Paho issue). When the client of 
the consumer hangs that way at the end of
- * the run, the world does not check that every message is routed, and a hung 
client is not checked for being closed;
+ * One case is looked at separately. A connect of a client that comes while 
the callback thread of that client is still
+ * in messageArrived after the connection closed never completes in Paho 1.2.5 
(CAMEL-27043, reproduced against a broker
+ * in PahoMqtt5ConsumerReconnectWhileRoutingTest): the client stays 
connecting, the consumer delivers nothing more, and
+ * the stop cannot close the client. The reconnect of the consumer after a 
failed message connects a new client (a new
+ * fake client here, with its own callback state), so only the automatic 
reconnect of Paho, while another message is in
+ * the route, still hangs that way. When the client of the consumer hangs at 
the end of the run, the world does not
+ * check that every message is routed, and a hung client is not checked for 
being closed;
  * {@code -Ddst.paho.strictCallbackThread=true} checks both. The operator also 
stops the route while the client
  * connects: the close of a connecting client fails in Paho (32110), and the 
consumer then forces the disconnect before
  * it closes the client again (CAMEL-27041).
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 1b6a4d066081..b70db850eb10 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -5919,7 +5919,9 @@ nothing more (the client completes the QoS 2 flow on its 
own, so QoS 2 messages
 QoS 1 message on a session that the broker keeps after the disconnect 
(`cleanStart=false` and `sessionExpiryInterval`
 greater than 0), the consumer connects again after a failed exchange (after 
one second, doubled for each failed
 exchange in a row up to `maxReconnectDelay`, and back to one second after any 
exchange that succeeds; logged at WARN),
-and the broker sends the message again. In all other
+and the broker sends the message again. For that the consumer closes its 
client and connects a new one with the same
+client id, so `getClient()` of the consumer returns another instance 
afterwards, and an exchange still in the route on
+the closed client is not acknowledged (the broker sends its message again, so 
that message is routed twice). In all other
 cases (a clean session, which is the default, a QoS 2 message, or 
`cleanStart=false` without `sessionExpiryInterval`,
 where the session ends with the connection) the broker never sends the message 
again, so the failed message is
 acknowledged and the failure is left to the Camel error handler. A consumer 
that uses a client set with the `client`

Reply via email to