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 2d3b83911887 CAMEL-27332: camel-mllp - a connection accepted just 
before the consumer stops is not served after the stop (#30704)
2d3b83911887 is described below

commit 2d3b839118874ba99b39498f8ff725470d017ce7
Author: allthingssecurity <[email protected]>
AuthorDate: Tue Nov 24 15:37:10 2026 +0530

    CAMEL-27332: camel-mllp - a connection accepted just before the consumer 
stops is not served after the stop (#30704)
    
    A connection still in its validation read when the consumer stopped was
    handed to startConsumer afterwards, which submitted a consumer runnable to 
the
    executor that doStop does not stop: the stopped route served the connection
    and answered every message with a NACK, and after a restart it was served
    next to the connections of the new start. startConsumer now resets such a
    connection when the consumer is not run-allowed (checked after the runnable 
is
    in consumerRunnables, so the stop's sweep or the check catches it), the
    runnable's running flag is volatile and true from construction so a stop()
    before run() is not undone, and doStop shuts down the executors of that 
start.
    
    The same can happen with lenientBind, where the bind thread retries while
    the port is busy. When the bind completed while the consumer stopped, the
    bind thread could call startAcceptThread after doStop had looked for an
    accept thread to stop: the stopped route kept listening on the port and
    accepting connections, and the port stayed held, so the route could not
    bind it again. A bind attempt still running when the interrupted bind
    thread gave up could also leave a bound socket that nothing closed.
    startAcceptThread and the accept-thread step of doStop now share a lock,
    and startAcceptThread closes the server socket when the consumer is not
    run-allowed; the bind thread closes the server socket when the bind task
    did not succeed.
    
    Found with a TLA+ model.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../component/mllp/MllpTcpServerConsumer.java      | 109 ++++++--
 .../mllp/internal/TcpServerBindThread.java         |   8 +-
 .../TcpServerConsumerValidationRunnable.java       |  25 +-
 .../mllp/internal/TcpSocketConsumerRunnable.java   |  10 +-
 .../MllpTcpServerConsumerLenientBindStopTest.java  | 180 ++++++++++++++
 .../mllp/MllpTcpServerConsumerStopTest.java        | 273 +++++++++++++++++++++
 6 files changed, 585 insertions(+), 20 deletions(-)

diff --git 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpTcpServerConsumer.java
 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpTcpServerConsumer.java
index 53458f17a910..680e5f05fe07 100644
--- 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpTcpServerConsumer.java
+++ 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpTcpServerConsumer.java
@@ -30,6 +30,8 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 import java.util.regex.Pattern;
 
 import javax.net.ssl.SSLPeerUnverifiedException;
@@ -55,6 +57,7 @@ import 
org.apache.camel.processor.mllp.Hl7AcknowledgementGenerationException;
 import org.apache.camel.spi.ThreadPoolProfile;
 import org.apache.camel.support.DefaultConsumer;
 import org.apache.camel.support.ExchangeHelper;
+import org.apache.camel.util.IOHelper;
 import org.apache.camel.util.concurrent.ThreadPoolRejectedPolicy;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -73,6 +76,9 @@ public class MllpTcpServerConsumer extends DefaultConsumer {
     ExecutorService consumerExecutor;
     TcpServerBindThread bindThread;
     TcpServerAcceptThread acceptThread;
+    // the bind thread starts the accept thread, doStop stops it: the lock 
makes the check of the consumer state (and of
+    // the bind thread of the current start) in startAcceptThread and the 
start atomic with respect to doStop and doStart
+    private final Lock acceptThreadLock = new ReentrantLock();
 
     Map<TcpSocketConsumerRunnable, Long> consumerRunnables = new 
ConcurrentHashMap<>();
 
@@ -137,15 +143,26 @@ public class MllpTcpServerConsumer extends 
DefaultConsumer {
             consumerClientSocketThread.stop();
         }
 
-        if (acceptThread != null) {
-            acceptThread.interrupt();
-            acceptThread = null;
+        acceptThreadLock.lock();
+        try {
+            if (acceptThread != null) {
+                acceptThread.interrupt();
+                acceptThread = null;
+            }
+            // under the same lock: a bind thread of this start that did not 
start its accept thread yet no longer owns
+            // the consumer, also when the consumer is started again before it 
gets there
+            if (bindThread != null) {
+                bindThread.interrupt();
+                bindThread = null;
+            }
+        } finally {
+            acceptThreadLock.unlock();
         }
 
-        if (bindThread != null) {
-            bindThread.interrupt();
-            bindThread = null;
-        }
+        // the executors of this start (doStart creates new ones): running 
runnables end on their own, and a connection
+        // still being validated is reset by startConsumer
+        
getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(validationExecutor);
+        
getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(consumerExecutor);
 
         super.doStop();
     }
@@ -172,14 +189,20 @@ public class MllpTcpServerConsumer extends 
DefaultConsumer {
                 .newThreadPool(this, "MllpConsumer", consumerProfile);
 
         if (bindThread == null || !bindThread.isAlive()) {
-            bindThread = new TcpServerBindThread(this, 
getEndpoint().getSslContextParameters());
+            TcpServerBindThread newBindThread = new TcpServerBindThread(this, 
getEndpoint().getSslContextParameters());
+            acceptThreadLock.lock();
+            try {
+                bindThread = newBindThread;
+            } finally {
+                acceptThreadLock.unlock();
+            }
 
             if (getConfiguration().isLenientBind()) {
                 log.debug("doStart() - starting bind thread");
-                bindThread.start();
+                newBindThread.start();
             } else {
                 log.debug("doStart() - attempting to bind to port {}", 
getEndpoint().getPort());
-                bindThread.run();
+                newBindThread.run();
 
                 if (this.acceptThread == null) {
                     throw new BindException("Failed to bind to port " + 
getEndpoint().getPort());
@@ -193,8 +216,11 @@ public class MllpTcpServerConsumer extends DefaultConsumer 
{
     @Override
     protected void doShutdown() throws Exception {
         super.doShutdown();
+        // doStop already shut the executors down, so the shutdownNow of the 
ExecutorServiceManager does nothing for them:
+        // the JDK shutdownNow still interrupts the running runnables (with 
virtual threads, this closes their sockets)
         if (consumerExecutor != null) {
             
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(consumerExecutor);
+            consumerExecutor.shutdownNow();
             consumerExecutor = null;
         }
         if (acceptThread != null) {
@@ -202,6 +228,7 @@ public class MllpTcpServerConsumer extends DefaultConsumer {
         }
         if (validationExecutor != null) {
             
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(validationExecutor);
+            validationExecutor.shutdownNow();
             validationExecutor = null;
         }
     }
@@ -224,7 +251,11 @@ public class MllpTcpServerConsumer extends DefaultConsumer 
{
 
     public void validateConsumer(Socket clientSocket) {
         MllpSocketBuffer mllpBuffer = new MllpSocketBuffer(getEndpoint());
-        TcpServerConsumerValidationRunnable client = new 
TcpServerConsumerValidationRunnable(this, clientSocket, mllpBuffer);
+        // the consumer executor of this start: when the consumer stops and 
starts again during the validation read, the
+        // connection is submitted to this executor, which doStop shut down, 
so it is reset and not served next to the
+        // connections of the new start
+        TcpServerConsumerValidationRunnable client
+                = new TcpServerConsumerValidationRunnable(this, clientSocket, 
mllpBuffer, consumerExecutor);
 
         try {
             log.debug("validateConsumer({}) - submitting client for 
validation", clientSocket);
@@ -236,8 +267,33 @@ public class MllpTcpServerConsumer extends DefaultConsumer 
{
     }
 
     public void startAcceptThread(ServerSocket serverSocket) {
-        acceptThread = new TcpServerAcceptThread(this, serverSocket);
-        acceptThread.start();
+        startAcceptThread(serverSocket, null);
+    }
+
+    /**
+     * Starts the accept thread on the server socket the bind thread bound.
+     *
+     * @param serverSocket the bound server socket
+     * @param owner        the bind thread that bound it: when it is not the 
bind thread of the current start (the
+     *                     consumer was stopped and started again in the 
meantime), the server socket is closed instead;
+     *                     <tt>null</tt> to only check that the consumer is 
not stopping or stopped
+     */
+    public void startAcceptThread(ServerSocket serverSocket, 
TcpServerBindThread owner) {
+        acceptThreadLock.lock();
+        try {
+            if (!isRunAllowed() || owner != null && owner != bindThread) {
+                // with lenientBind the bind thread can bind while the 
consumer stops, after doStop looked for an
+                // accept thread to stop: do not start one after the stop (nor 
for the next start), and release the port
+                log.debug("startAcceptThread({}) - the consumer is stopping or 
stopped, closing the server socket",
+                        serverSocket);
+                IOHelper.close(serverSocket);
+                return;
+            }
+            acceptThread = new TcpServerAcceptThread(this, serverSocket);
+            acceptThread.start();
+        } finally {
+            acceptThreadLock.unlock();
+        }
     }
 
     /**
@@ -249,16 +305,39 @@ public class MllpTcpServerConsumer extends 
DefaultConsumer {
     }
 
     public void startConsumer(Socket clientSocket, MllpSocketBuffer 
mllpBuffer) {
+        startConsumer(clientSocket, mllpBuffer, consumerExecutor);
+    }
+
+    /**
+     * Serves a validated connection.
+     *
+     * @param clientSocket the connection
+     * @param mllpBuffer   the data of the validation read
+     * @param executor     the consumer executor of the start that accepted 
the connection: it is shut down when that
+     *                     start was stopped, and the connection is then reset
+     */
+    public void startConsumer(Socket clientSocket, MllpSocketBuffer 
mllpBuffer, ExecutorService executor) {
         TcpSocketConsumerRunnable client = new TcpSocketConsumerRunnable(
                 this, clientSocket, mllpBuffer, hl7Util, logPhi);
 
         consumerRunnables.put(client, System.currentTimeMillis());
+        if (!isRunAllowed()) {
+            // the consumer is stopping or stopped (the connection was 
accepted just before): do not serve it. The check
+            // comes after the put, so the runnable is either seen by the loop 
of doStop, or not started here
+            consumerRunnables.remove(client);
+            mllpBuffer.resetSocket(clientSocket, "Consumer is stopped");
+            return;
+        }
         try {
             log.info("startConsumer({}) - starting consumer", clientSocket);
-            consumerExecutor.submit(client);
+            executor.submit(client);
             getEndpoint().updateLastConnectionEstablishedTicks();
         } catch (RejectedExecutionException rejectedExecutionEx) {
-            log.warn("startConsumer({}) - cannot start consumer - max 
consumers already active", clientSocket);
+            if (executor.isShutdown()) {
+                log.debug("startConsumer({}) - cannot start consumer - the 
start that accepted it was stopped", clientSocket);
+            } else {
+                log.warn("startConsumer({}) - cannot start consumer - max 
consumers already active", clientSocket);
+            }
             // the runnable never runs, so it does not remove itself
             consumerRunnables.remove(client);
             mllpBuffer.resetSocket(clientSocket);
diff --git 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerBindThread.java
 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerBindThread.java
index 70a758a0e79a..2228ce818d3f 100644
--- 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerBindThread.java
+++ 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerBindThread.java
@@ -34,6 +34,7 @@ import org.apache.camel.support.jsse.SSLContextParameters;
 import org.apache.camel.support.task.BlockingTask;
 import org.apache.camel.support.task.Tasks;
 import org.apache.camel.support.task.budget.Budgets;
+import org.apache.camel.util.IOHelper;
 import org.apache.camel.util.StringHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -115,10 +116,15 @@ public class TcpServerBindThread extends Thread {
                     .build();
 
             if (task.run(consumer.getEndpoint().getCamelContext(), () -> 
doBind(serverSocket, socketAddress))) {
-                consumer.startAcceptThread(serverSocket);
+                // closes the socket instead when the consumer stopped in the 
meantime, or was started again (then this
+                // is no longer the bind thread of the current start)
+                consumer.startAcceptThread(serverSocket, this);
             } else {
                 log.error("Failed to bind to address {} within timeout {}", 
socketAddress,
                         consumer.getConfiguration().getBindTimeout());
+                // no accept thread closes this socket: a bind attempt that 
was still running when the task gave up (the
+                // consumer stopped) can have bound it, and would hold the port
+                IOHelper.close(serverSocket);
             }
         } finally {
             
consumer.getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(ses);
diff --git 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerConsumerValidationRunnable.java
 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerConsumerValidationRunnable.java
index 024619dc9b60..7bdbe1c3e27f 100644
--- 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerConsumerValidationRunnable.java
+++ 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpServerConsumerValidationRunnable.java
@@ -20,6 +20,7 @@ import java.io.IOException;
 import java.net.Socket;
 import java.net.SocketAddress;
 import java.net.SocketTimeoutException;
+import java.util.concurrent.ExecutorService;
 
 import org.apache.camel.Route;
 import org.apache.camel.component.mllp.MllpSocketException;
@@ -39,6 +40,8 @@ public class TcpServerConsumerValidationRunnable implements 
Runnable {
 
     Logger log = LoggerFactory.getLogger(this.getClass());
     MllpTcpServerConsumer consumer;
+    // the consumer executor of the start that accepted the connection (null: 
the current one of the consumer)
+    private final ExecutorService consumerExecutor;
 
     private final String localAddress;
     private final String remoteAddress;
@@ -46,7 +49,17 @@ public class TcpServerConsumerValidationRunnable implements 
Runnable {
 
     public TcpServerConsumerValidationRunnable(MllpTcpServerConsumer consumer, 
Socket clientSocket,
                                                MllpSocketBuffer mllpBuffer) {
+        this(consumer, clientSocket, mllpBuffer, null);
+    }
+
+    /**
+     * @param consumerExecutor the consumer executor of the start that 
accepted the connection, which serves it (when
+     *                         that start was stopped, it is shut down and the 
connection is reset)
+     */
+    public TcpServerConsumerValidationRunnable(MllpTcpServerConsumer consumer, 
Socket clientSocket,
+                                               MllpSocketBuffer mllpBuffer, 
ExecutorService consumerExecutor) {
         this.consumer = consumer;
+        this.consumerExecutor = consumerExecutor;
         // this.setName(createThreadName(clientSocket));
         this.clientSocket = clientSocket;
 
@@ -136,7 +149,7 @@ public class TcpServerConsumerValidationRunnable implements 
Runnable {
             mllpBuffer.readFrom(clientSocket, Math.min(500, 
consumer.getConfiguration().getReceiveTimeout()),
                     consumer.getConfiguration().getReadTimeout());
             if (mllpBuffer.hasCompleteEnvelope() || 
mllpBuffer.hasStartOfBlock()) {
-                consumer.startConsumer(clientSocket, mllpBuffer);
+                startConsumer();
             } else if (!mllpBuffer.isEmpty()) {
                 // We have some leading out-of-band data but no START_OF_BLOCK
                 log.info("Ignoring out-of-band data on initial read [{} 
bytes]: {}", mllpBuffer.size(),
@@ -153,7 +166,7 @@ public class TcpServerConsumerValidationRunnable implements 
Runnable {
         } catch (SocketTimeoutException timeoutEx) {
             if (mllpBuffer.isEmpty()) {
                 log.debug("Initial read timed-out but no data was read - 
starting consumer");
-                consumer.startConsumer(clientSocket, mllpBuffer);
+                startConsumer();
             } else {
                 log.warn("Timeout receiving complete initial message on read 
[{} bytes]: {}", mllpBuffer.size(),
                         mllpBuffer.toLoggableStringAndReset());
@@ -164,6 +177,14 @@ public class TcpServerConsumerValidationRunnable 
implements Runnable {
         }
     }
 
+    private void startConsumer() {
+        if (consumerExecutor != null) {
+            consumer.startConsumer(clientSocket, mllpBuffer, consumerExecutor);
+        } else {
+            consumer.startConsumer(clientSocket, mllpBuffer);
+        }
+    }
+
     public void closeSocket() {
         mllpBuffer.closeSocket(clientSocket);
     }
diff --git 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpSocketConsumerRunnable.java
 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpSocketConsumerRunnable.java
index db05e0120398..38d8759e542d 100644
--- 
a/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpSocketConsumerRunnable.java
+++ 
b/components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/TcpSocketConsumerRunnable.java
@@ -41,7 +41,8 @@ public class TcpSocketConsumerRunnable implements Runnable {
 
     Logger log = LoggerFactory.getLogger(this.getClass());
     MllpTcpServerConsumer consumer;
-    boolean running;
+    // true from the start, so a stop() before run() is not undone; written by 
the stopping thread
+    volatile boolean running = true;
 
     private final String localAddress;
     private final String remoteAddress;
@@ -122,7 +123,6 @@ public class TcpSocketConsumerRunnable implements Runnable {
     @SuppressWarnings("deprecation")
     // MDC deprecated since 4.19.0, use camel-mdc instead
     public void run() {
-        running = true;
         String originalThreadName = Thread.currentThread().getName();
         Thread.currentThread().setName(createThreadName());
         MDC.put(UnitOfWork.MDC_CAMEL_CONTEXT_ID, 
consumer.getEndpoint().getCamelContext().getName());
@@ -137,6 +137,12 @@ public class TcpSocketConsumerRunnable implements Runnable 
{
 
         log.debug("Starting {} for {}", this.getClass().getSimpleName(), 
combinedAddress);
         try {
+            if (!running) {
+                // stopped between the check of startConsumer and the submit: 
the messages of the validation read are not
+                // sent to the stopping route (the finally block removes this 
runnable and resets the socket)
+                log.debug("{} for {} was stopped before it ran", 
this.getClass().getSimpleName(), combinedAddress);
+                return;
+            }
             if (mllpBuffer.hasCompleteEnvelope()) {
                 // Process all complete messages received during the 
validation read.
                 processBufferedMessages();
diff --git 
a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerLenientBindStopTest.java
 
b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerLenientBindStopTest.java
new file mode 100644
index 000000000000..22133dd843a6
--- /dev/null
+++ 
b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerLenientBindStopTest.java
@@ -0,0 +1,180 @@
+/*
+ * 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.mllp;
+
+import java.net.ServerSocket;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.component.mllp.internal.TcpServerBindThread;
+import org.apache.camel.test.AvailablePortFinder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.awaitility.Awaitility;
+import org.awaitility.core.ConditionFactory;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With lenientBind the consumer binds its port in a background thread, which 
retries while the port is busy. When the
+ * port is freed while the consumer stops, the bind can complete after doStop 
looked for an accept thread to stop: no
+ * accept thread must start after the stop, and the port must be released.
+ */
+class MllpTcpServerConsumerLenientBindStopTest extends CamelTestSupport {
+
+    @RegisterExtension
+    AvailablePortFinder.Port port = AvailablePortFinder.find();
+
+    // released when the consumer has stopped, or when the test ends (so the 
bind thread that waits for it never hangs)
+    private final CountDownLatch stopped = new CountDownLatch(1);
+    private MllpTcpServerConsumer consumer;
+
+    @AfterEach
+    void stopConsumer() {
+        stopped.countDown();
+        if (consumer != null) {
+            consumer.stop();
+        }
+    }
+
+    @Test
+    void testBindCompletingDuringStopDoesNotStartAcceptThread() throws 
Exception {
+        CountDownLatch bound = new CountDownLatch(1);
+        AtomicReference<ServerSocket> boundSocket = new AtomicReference<>();
+        consumer = new MllpTcpServerConsumer(lenientEndpoint(), exchange -> {
+        }) {
+            @Override
+            public void startAcceptThread(ServerSocket serverSocket, 
TcpServerBindThread owner) {
+                // the bind thread has bound the port: let the consumer stop 
before it starts the accept thread
+                boundSocket.set(serverSocket);
+                bound.countDown();
+                awaitUninterruptibly(stopped);
+                super.startAcceptThread(serverSocket, owner);
+            }
+        };
+
+        try (ServerSocket busy = new ServerSocket(port.getPort())) {
+            consumer.start();
+            // the port is busy: the bind thread retries
+            await().atMost(5, TimeUnit.SECONDS).until(() -> 
threads("TcpServerBindThread") == 1);
+        }
+
+        // the port is free now: the next attempt binds it, and the route 
stops at the same time
+        assertTrue(bound.await(10, TimeUnit.SECONDS), "the bind thread must 
bind the freed port");
+        consumer.stop();
+        stopped.countDown();
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpServerBindThread") == 0);
+        assertEquals(0, threads("TcpServerAcceptThread"), "no accept thread 
must run after the stop");
+        assertTrue(boundSocket.get().isClosed(), "the stopped consumer must 
release its port");
+    }
+
+    @Test
+    void 
testBindOfPreviousStartCompletingAfterRestartDoesNotStartAcceptThread() throws 
Exception {
+        CountDownLatch bound = new CountDownLatch(1);
+        AtomicReference<ServerSocket> boundSocket = new AtomicReference<>();
+        AtomicBoolean first = new AtomicBoolean(true);
+        consumer = new MllpTcpServerConsumer(lenientEndpoint(), exchange -> {
+        }) {
+            @Override
+            public void startAcceptThread(ServerSocket serverSocket, 
TcpServerBindThread owner) {
+                if (first.getAndSet(false)) {
+                    // the bind thread of the first start has bound the port: 
let the consumer stop and start again
+                    // before it starts the accept thread
+                    boundSocket.set(serverSocket);
+                    bound.countDown();
+                    awaitUninterruptibly(stopped);
+                }
+                super.startAcceptThread(serverSocket, owner);
+            }
+        };
+
+        try (ServerSocket busy = new ServerSocket(port.getPort())) {
+            consumer.start();
+            await().atMost(5, TimeUnit.SECONDS).until(() -> 
threads("TcpServerBindThread") == 1);
+        }
+
+        assertTrue(bound.await(10, TimeUnit.SECONDS), "the bind thread must 
bind the freed port");
+        // a quick restart: the new start has its own bind thread, which 
retries while the old one holds the port
+        consumer.stop();
+        consumer.start();
+        stopped.countDown();
+
+        // the bind thread of the first start closes its socket instead of 
starting an accept thread for the new start,
+        // and the bind thread of the new start then binds the port and starts 
the only accept thread
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
boundSocket.get().isClosed());
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpServerAcceptThread") == 1);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpServerBindThread") == 0);
+        assertEquals(1, threads("TcpServerAcceptThread"));
+        assertEquals(port.getPort(), consumer.getLocalPort());
+    }
+
+    @Test
+    void testStopWhileBindRetriesReleasesPort() throws Exception {
+        consumer = new MllpTcpServerConsumer(lenientEndpoint(), exchange -> {
+        });
+
+        try (ServerSocket busy = new ServerSocket(port.getPort())) {
+            consumer.start();
+            await().atMost(5, TimeUnit.SECONDS).until(() -> 
threads("TcpServerBindThread") == 1);
+            consumer.stop();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpServerBindThread") == 0);
+        }
+
+        assertEquals(0, threads("TcpServerAcceptThread"), "the stopped 
consumer must not bind the freed port");
+    }
+
+    private MllpEndpoint lenientEndpoint() {
+        return context.getEndpoint(
+                "mllp://localhost:" + port.getPort() + 
"?lenientBind=true&bindRetryInterval=100&bindTimeout=30000",
+                MllpEndpoint.class);
+    }
+
+    private static ConditionFactory await() {
+        // the tests of the module run in parallel: an exception in a thread 
of another test must not fail the wait
+        return Awaitility.await().dontCatchUncaughtExceptions();
+    }
+
+    private long threads(String prefix) {
+        return Thread.getAllStackTraces().keySet().stream()
+                .filter(t -> t.isAlive() && t.getName().startsWith(prefix)
+                        && t.getName().contains("localhost:" + port.getPort()))
+                .count();
+    }
+
+    private static void awaitUninterruptibly(CountDownLatch latch) {
+        // doStop interrupts the bind thread while it waits here; keep the 
interrupt for the code that follows
+        boolean interrupted = false;
+        while (true) {
+            try {
+                if (latch.await(10, TimeUnit.SECONDS)) {
+                    break;
+                }
+            } catch (InterruptedException e) {
+                interrupted = true;
+            }
+        }
+        if (interrupted) {
+            Thread.currentThread().interrupt();
+        }
+    }
+}
diff --git 
a/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerStopTest.java
 
b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerStopTest.java
new file mode 100644
index 000000000000..fa4f6cf67b9f
--- /dev/null
+++ 
b/components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerStopTest.java
@@ -0,0 +1,273 @@
+/*
+ * 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.mllp;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.Processor;
+import org.apache.camel.component.mllp.internal.MllpSocketBuffer;
+import org.apache.camel.test.AvailablePortFinder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.awaitility.Awaitility;
+import org.awaitility.core.ConditionFactory;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A connection that the consumer accepted, and was still validating (its 
first read) when the consumer stopped, must
+ * not be served after the stop, nor next to the connections of the next 
start. A route stop, or a suspend and resume by
+ * a route policy, stops and starts the consumer, as the tests do.
+ */
+class MllpTcpServerConsumerStopTest extends CamelTestSupport {
+
+    static final String MESSAGE = 
"MSH|^~\\&|ADT|EPIC|JCAPS|CC|20160902123950|RISTECH|ADT^A08|00001|D|2.3|||||||\r";
+
+    @RegisterExtension
+    AvailablePortFinder.Port port = AvailablePortFinder.find();
+
+    // when set, the next connection that ends its validation read waits for 
this latch before startConsumer runs
+    private final AtomicReference<CountDownLatch> holdNextValidated = new 
AtomicReference<>();
+    private final CountDownLatch validated = new CountDownLatch(1);
+    private MllpTcpServerConsumer consumer;
+
+    @AfterEach
+    void stopConsumer() {
+        CountDownLatch hold = holdNextValidated.getAndSet(null);
+        if (hold != null) {
+            hold.countDown();
+        }
+        if (consumer != null) {
+            consumer.shutdown();
+        }
+    }
+
+    @Test
+    void testConnectionValidatedDuringStopIsNotServed() throws Exception {
+        consumer = new HeldConsumer(endpoint(), exchange -> {
+        });
+        consumer.start();
+        CountDownLatch release = new CountDownLatch(1);
+        try (Socket client = connectAndHoldAfterValidation(release)) {
+            consumer.stop();
+            release.countDown();
+
+            // the validation read ended before the stop, and startConsumer 
runs after it: the connection is reset
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpServerConsumerValidationRunnable") == 0);
+            assertEquals(0, threads("TcpSocketConsumerRunnable"));
+            assertTrue(consumer.getConsumerRunnables().isEmpty());
+            assertEquals("", sendAndReadAck(client), "the stopped consumer 
must not answer");
+        }
+    }
+
+    @Test
+    void testConnectionValidatedDuringStopIsNotServedAfterRestart() throws 
Exception {
+        consumer = new HeldConsumer(endpoint(), exchange -> {
+        });
+        consumer.start();
+        CountDownLatch release = new CountDownLatch(1);
+        try (Socket client1 = connectAndHoldAfterValidation(release)) {
+            consumer.stop();
+            release.countDown();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpServerConsumerValidationRunnable") == 0);
+            consumer.start();
+
+            // a new connection is served after the restart, and the old one 
is not (maxConcurrentConsumers=1)
+            try (Socket client2 = new Socket("localhost", port.getPort())) {
+                assertTrue(sendAndReadAck(client2).contains("MSA|AA"));
+                assertEquals("", sendAndReadAck(client1), "the connection of 
the previous start must not be served");
+                assertEquals(1, threads("TcpSocketConsumerRunnable"));
+            }
+        }
+    }
+
+    @Test
+    void testConnectionValidatedDuringRestartIsNotServedAfterRestart() throws 
Exception {
+        consumer = new HeldConsumer(endpoint(), exchange -> {
+        });
+        consumer.start();
+        CountDownLatch release = new CountDownLatch(1);
+        try (Socket client1 = connectAndHoldAfterValidation(release)) {
+            // the consumer stops and starts again (such as a suspend and 
resume by a route policy) before the
+            // connection of the previous start reaches startConsumer, so the 
consumer is run-allowed again by then
+            consumer.stop();
+            consumer.start();
+            release.countDown();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpServerConsumerValidationRunnable") == 0);
+
+            // it is not served next to the connections of the new start, nor 
counted against its maxConcurrentConsumers
+            assertEquals(0, threads("TcpSocketConsumerRunnable"));
+            assertTrue(consumer.getConsumerRunnables().isEmpty());
+            try (Socket client2 = new Socket("localhost", port.getPort())) {
+                assertTrue(sendAndReadAck(client2).contains("MSA|AA"));
+                assertEquals("", sendAndReadAck(client1), "the connection of 
the previous start must not be served");
+                assertEquals(1, threads("TcpSocketConsumerRunnable"));
+            }
+        }
+    }
+
+    @Test
+    void testConnectionServedBeforeStopEndsWithinReceiveTimeout() throws 
Exception {
+        consumer = new HeldConsumer(endpoint(), exchange -> {
+        });
+        consumer.start();
+        try (Socket client = new Socket("localhost", port.getPort())) {
+            assertTrue(sendAndReadAck(client).contains("MSA|AA"));
+            assertEquals(1, threads("TcpSocketConsumerRunnable"));
+
+            consumer.stop();
+
+            await().atMost(10, TimeUnit.SECONDS).until(() -> 
threads("TcpSocketConsumerRunnable") == 0);
+        }
+    }
+
+    @Test
+    void testShutdownInterruptsTheRunnableServingAConnection() throws 
Exception {
+        CountDownLatch processing = new CountDownLatch(1);
+        CountDownLatch interrupted = new CountDownLatch(1);
+        consumer = new HeldConsumer(endpoint(), exchange -> {
+            processing.countDown();
+            try {
+                // blocks like a slow processor until it is interrupted
+                new CountDownLatch(1).await(20, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                interrupted.countDown();
+                Thread.currentThread().interrupt();
+            }
+        });
+        consumer.start();
+        try (Socket client = new Socket("localhost", port.getPort())) {
+            send(client);
+            assertTrue(processing.await(10, TimeUnit.SECONDS), "the message 
must be processed");
+
+            // the stop shuts the executors down without interrupting the 
runnables, the shutdown must interrupt them
+            // (with virtual threads, the interrupt also closes the socket of 
a connection blocked in its read)
+            consumer.stop();
+            consumer.shutdown();
+            assertTrue(interrupted.await(5, TimeUnit.SECONDS),
+                    "the shutdown must interrupt the runnable that serves the 
connection");
+        }
+    }
+
+    private MllpEndpoint endpoint() {
+        return context.getEndpoint(
+                "mllp://localhost:" + port.getPort()
+                                   + 
"?maxConcurrentConsumers=1&reuseAddress=true&receiveTimeout=2000&autoAck=true",
+                MllpEndpoint.class);
+    }
+
+    /**
+     * Connects without sending: the accept thread hands the socket to a 
validation runnable, whose read (500 ms) ends
+     * without data. It then waits for the latch before it calls 
startConsumer, so the test can stop (and start) the
+     * consumer in between, standing in for a stop that lands during the 
validation read.
+     */
+    private Socket connectAndHoldAfterValidation(CountDownLatch release) 
throws Exception {
+        holdNextValidated.set(release);
+        Socket client = new Socket("localhost", port.getPort());
+        assertTrue(validated.await(10, TimeUnit.SECONDS), "the validation read 
must end");
+        return client;
+    }
+
+    private final class HeldConsumer extends MllpTcpServerConsumer {
+
+        HeldConsumer(MllpEndpoint endpoint, Processor processor) {
+            super(endpoint, processor);
+        }
+
+        @Override
+        public void startConsumer(Socket clientSocket, MllpSocketBuffer 
mllpBuffer, ExecutorService executor) {
+            CountDownLatch hold = holdNextValidated.getAndSet(null);
+            if (hold != null) {
+                validated.countDown();
+                awaitUninterruptibly(hold);
+            }
+            super.startConsumer(clientSocket, mllpBuffer, executor);
+        }
+    }
+
+    private static void awaitUninterruptibly(CountDownLatch latch) {
+        // the shutdown of the validation executor at the end of a test 
interrupts the thread that waits here
+        boolean interrupted = false;
+        while (true) {
+            try {
+                if (latch.await(10, TimeUnit.SECONDS)) {
+                    break;
+                }
+            } catch (InterruptedException e) {
+                interrupted = true;
+            }
+        }
+        if (interrupted) {
+            Thread.currentThread().interrupt();
+        }
+    }
+
+    private static ConditionFactory await() {
+        // the tests of the module run in parallel: an exception in a thread 
of another test must not fail the wait
+        return Awaitility.await().dontCatchUncaughtExceptions();
+    }
+
+    private long threads(String prefix) {
+        return Thread.getAllStackTraces().keySet().stream()
+                .filter(t -> t.isAlive() && t.getName().startsWith(prefix)
+                        && t.getName().contains(":" + port.getPort() + "]"))
+                .count();
+    }
+
+    /**
+     * Sends a message and returns the acknowledgement, or an empty string 
when the connection is closed or reset.
+     */
+    private static String sendAndReadAck(Socket socket) throws IOException {
+        ByteArrayOutputStream ack = new ByteArrayOutputStream();
+        try {
+            send(socket);
+            socket.setSoTimeout(5000);
+            InputStream in = socket.getInputStream();
+            int b;
+            while ((b = in.read()) != -1 && b != 0x1c) {
+                if (b != 0x0b) {
+                    ack.write(b);
+                }
+            }
+        } catch (IOException e) {
+            // reset by the consumer
+            return "";
+        }
+        return ack.toString(StandardCharsets.ISO_8859_1);
+    }
+
+    private static void send(Socket socket) throws IOException {
+        OutputStream out = socket.getOutputStream();
+        out.write(0x0b);
+        out.write(MESSAGE.getBytes(StandardCharsets.ISO_8859_1));
+        out.write(0x1c);
+        out.write(0x0d);
+        out.flush();
+    }
+}

Reply via email to