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 d3bbea85b716 CAMEL-27003: camel-alibaba-mns, camel-alibaba-oss - 
create the client once (#30120)
d3bbea85b716 is described below

commit d3bbea85b7166d8a30a863f129a960567b800825
Author: Saravanakumar Selvaraj <[email protected]>
AuthorDate: Sun Nov 15 22:02:43 2026 +0000

    CAMEL-27003: camel-alibaba-mns, camel-alibaba-oss - create the client once 
(#30120)
    
    … once
    
    MNSEndpoint.initClient, which the producer calls for each message and the
    consumer for each poll, and OSSEndpoint.initClient, which the producer
    calls while it has no client and the consumer calls when it starts, read
    and wrote the client field without a lock, and the field was not
    volatile. Calls made at the same time before a client existed could each
    create a client. The endpoint kept only the last one, and doStop closed
    only that one, so the others were never closed. The MNS clients that the
    endpoint creates share one service client of the MNS SDK, so a client
    that was not closed also kept the HTTP client of that service client and
    its threads running after the endpoint had stopped.
    
    initClient now creates the client under the lock that the endpoint
    inherits from BaseService and reads the field, now volatile, again inside
    it, so only one client is created, and a call does not take the lock once
    the client exists. The signatures of initClient and the moment at which
    the producers and the consumers create the client do not change. The
    setter of the client and doStop take the same lock. The creation is in a
    package-private method createClient of each endpoint, which a test
    overrides to hold it.
    
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 components/camel-alibaba/camel-alibaba-mns/pom.xml |  7 ++
 .../camel/component/alibaba/mns/MNSEndpoint.java   | 45 ++++++++++---
 .../component/alibaba/mns/MNSEndpointTest.java     | 76 ++++++++++++++++++++++
 components/camel-alibaba/camel-alibaba-oss/pom.xml |  6 ++
 .../camel/component/alibaba/oss/OSSEndpoint.java   | 47 +++++++++----
 .../component/alibaba/oss/OSSEndpointTest.java     | 74 +++++++++++++++++++++
 6 files changed, 235 insertions(+), 20 deletions(-)

diff --git a/components/camel-alibaba/camel-alibaba-mns/pom.xml 
b/components/camel-alibaba/camel-alibaba-mns/pom.xml
index e947030333b7..61d62d0a545f 100644
--- a/components/camel-alibaba/camel-alibaba-mns/pom.xml
+++ b/components/camel-alibaba/camel-alibaba-mns/pom.xml
@@ -72,6 +72,13 @@
             <version>${mockito-version}</version>
             <scope>test</scope>
         </dependency>
+
+        <dependency>
+            <groupId>org.awaitility</groupId>
+            <artifactId>awaitility</artifactId>
+            <version>${awaitility-version}</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
 </project>
diff --git 
a/components/camel-alibaba/camel-alibaba-mns/src/main/java/org/apache/camel/component/alibaba/mns/MNSEndpoint.java
 
b/components/camel-alibaba/camel-alibaba-mns/src/main/java/org/apache/camel/component/alibaba/mns/MNSEndpoint.java
index d8b8295cf3b4..1add61f4a698 100644
--- 
a/components/camel-alibaba/camel-alibaba-mns/src/main/java/org/apache/camel/component/alibaba/mns/MNSEndpoint.java
+++ 
b/components/camel-alibaba/camel-alibaba-mns/src/main/java/org/apache/camel/component/alibaba/mns/MNSEndpoint.java
@@ -106,7 +106,7 @@ public class MNSEndpoint extends ScheduledPollEndpoint {
 
     @UriParam(description = "Autowire an existing MNSClient instance", 
displayName = "MNS Client", label = "advanced")
     @Metadata(autowired = true)
-    private MNSClient mnsClient;
+    private volatile MNSClient mnsClient;
 
     private boolean autowiredMnsClient;
 
@@ -135,18 +135,40 @@ public class MNSEndpoint extends ScheduledPollEndpoint {
         return consumer;
     }
 
+    /**
+     * Makes sure that this endpoint has the client that the producer and the 
consumer send their requests with, which
+     * they then get with {@link #getMnsClient()}. If no client is set or 
autowired, the first call creates it from the
+     * options of this endpoint, while it holds the lock of this endpoint: the 
calls made at the same time wait for this
+     * creation, and the calls made once the client exists do not take the 
lock. A failed creation keeps no client, so
+     * each call that waited for it, and each later call, tries again.
+     */
     public void initClient() {
-        if (mnsClient != null) {
-            return;
+        if (mnsClient == null) {
+            lock.lock();
+            try {
+                if (mnsClient == null) {
+                    mnsClient = createClient();
+                }
+            } finally {
+                lock.unlock();
+            }
         }
-        mnsClient = MNSUtils.createClient(this);
+    }
+
+    MNSClient createClient() {
+        return MNSUtils.createClient(this);
     }
 
     @Override
     protected void doStop() throws Exception {
-        if (mnsClient != null && !autowiredMnsClient) {
-            mnsClient.close();
-            mnsClient = null;
+        lock.lock();
+        try {
+            if (mnsClient != null && !autowiredMnsClient) {
+                mnsClient.close();
+                mnsClient = null;
+            }
+        } finally {
+            lock.unlock();
         }
         super.doStop();
     }
@@ -252,8 +274,13 @@ public class MNSEndpoint extends ScheduledPollEndpoint {
     }
 
     public void setMnsClient(MNSClient mnsClient) {
-        this.mnsClient = mnsClient;
-        this.autowiredMnsClient = mnsClient != null;
+        lock.lock();
+        try {
+            this.mnsClient = mnsClient;
+            this.autowiredMnsClient = mnsClient != null;
+        } finally {
+            lock.unlock();
+        }
     }
 
     public String resolveOperation() {
diff --git 
a/components/camel-alibaba/camel-alibaba-mns/src/test/java/org/apache/camel/component/alibaba/mns/MNSEndpointTest.java
 
b/components/camel-alibaba/camel-alibaba-mns/src/test/java/org/apache/camel/component/alibaba/mns/MNSEndpointTest.java
index 95dfa7712d09..f2c79fdf5a95 100644
--- 
a/components/camel-alibaba/camel-alibaba-mns/src/test/java/org/apache/camel/component/alibaba/mns/MNSEndpointTest.java
+++ 
b/components/camel-alibaba/camel-alibaba-mns/src/test/java/org/apache/camel/component/alibaba/mns/MNSEndpointTest.java
@@ -16,10 +16,24 @@
  */
 package org.apache.camel.component.alibaba.mns;
 
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
 import com.aliyun.mns.client.MNSClient;
 import org.junit.jupiter.api.Test;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
@@ -55,4 +69,66 @@ class MNSEndpointTest {
         verify(client).close();
         assertThat(endpoint.getMnsClient()).isNull();
     }
+
+    @Test
+    void concurrentInitClientCreatesOneClient() throws Exception {
+        int callers = 8;
+        Set<Thread> creators = ConcurrentHashMap.newKeySet();
+        List<MNSClient> created = new CopyOnWriteArrayList<>();
+        CountDownLatch release = new CountDownLatch(1);
+        MNSEndpoint endpoint = new MNSEndpoint() {
+            @Override
+            MNSClient createClient() {
+                creators.add(Thread.currentThread());
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                MNSClient client = mock(MNSClient.class);
+                created.add(client);
+                return client;
+            }
+        };
+
+        Set<Thread> threads = ConcurrentHashMap.newKeySet();
+        ExecutorService executor = Executors.newFixedThreadPool(callers);
+        try {
+            List<Future<MNSClient>> results = new ArrayList<>();
+            for (int i = 0; i < callers; i++) {
+                results.add(executor.submit(() -> {
+                    threads.add(Thread.currentThread());
+                    // as the producer and the consumer do, which then get the 
client from the endpoint
+                    endpoint.initClient();
+                    return endpoint.getMnsClient();
+                }));
+            }
+            // a creation is held until each caller has started one too, or 
waits for the lock of a caller that has,
+            // so the result does not depend on how the threads are scheduled
+            await().atMost(10, TimeUnit.SECONDS).until(() -> threads.size() == 
callers
+                    && threads.stream().allMatch(thread -> 
creators.contains(thread) || waitsForLockOf(thread, creators)));
+            release.countDown();
+
+            List<MNSClient> clients = new ArrayList<>();
+            for (Future<MNSClient> result : results) {
+                clients.add(result.get(10, TimeUnit.SECONDS));
+            }
+            assertThat(created).hasSize(1);
+            assertThat(clients).hasSize(callers).allSatisfy(client -> 
assertThat(client).isSameAs(created.get(0)));
+            assertThat(endpoint.getMnsClient()).isSameAs(created.get(0));
+
+            endpoint.doStop();
+            verify(created.get(0)).close();
+            assertThat(endpoint.getMnsClient()).isNull();
+        } finally {
+            release.countDown();
+            executor.shutdownNow();
+        }
+    }
+
+    private static boolean waitsForLockOf(Thread thread, Set<Thread> owners) {
+        ThreadInfo info = 
ManagementFactory.getThreadMXBean().getThreadInfo(thread.threadId());
+        return info != null && owners.stream().anyMatch(owner -> 
owner.threadId() == info.getLockOwnerId());
+    }
 }
diff --git a/components/camel-alibaba/camel-alibaba-oss/pom.xml 
b/components/camel-alibaba/camel-alibaba-oss/pom.xml
index d8038c899b21..93ddabaa214b 100644
--- a/components/camel-alibaba/camel-alibaba-oss/pom.xml
+++ b/components/camel-alibaba/camel-alibaba-oss/pom.xml
@@ -71,5 +71,11 @@
       <artifactId>assertj-core</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.awaitility</groupId>
+      <artifactId>awaitility</artifactId>
+      <version>${awaitility-version}</version>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 </project>
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSEndpoint.java
 
b/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSEndpoint.java
index 3de567b2b9e1..be887500c500 100644
--- 
a/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSEndpoint.java
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSEndpoint.java
@@ -125,7 +125,7 @@ public class OSSEndpoint extends ScheduledPollEndpoint {
 
     @UriParam(description = "An autowired OSS client", displayName = "OSS 
Client", label = "advanced")
     @Metadata(autowired = true)
-    private OSSClient ossClient;
+    private volatile OSSClient ossClient;
 
     private boolean autowiredOssClient;
 
@@ -151,22 +151,42 @@ public class OSSEndpoint extends ScheduledPollEndpoint {
     }
 
     /**
-     * Initialize and return an OSS client
+     * Returns the client that the producer and the consumer send their 
requests with. If no client is set or autowired,
+     * the first call creates it from the options of this endpoint, while it 
holds the lock of this endpoint: the calls
+     * made at the same time wait for this creation, and the calls made once 
the client exists do not take the lock. A
+     * failed creation keeps no client, so each call that waited for it, and 
each later call, tries again.
      */
     public OSSClient initClient() {
-        if (ossClient != null) {
-            return ossClient;
+        OSSClient answer = ossClient;
+        if (answer == null) {
+            lock.lock();
+            try {
+                answer = ossClient;
+                if (answer == null) {
+                    answer = createClient();
+                    ossClient = answer;
+                }
+            } finally {
+                lock.unlock();
+            }
         }
+        return answer;
+    }
 
-        ossClient = OSSUtils.createClient(this);
-        return ossClient;
+    OSSClient createClient() {
+        return OSSUtils.createClient(this);
     }
 
     @Override
     protected void doStop() throws Exception {
-        if (ossClient != null && !autowiredOssClient) {
-            ossClient.close();
-            ossClient = null;
+        lock.lock();
+        try {
+            if (ossClient != null && !autowiredOssClient) {
+                ossClient.close();
+                ossClient = null;
+            }
+        } finally {
+            lock.unlock();
         }
         super.doStop();
     }
@@ -280,7 +300,12 @@ public class OSSEndpoint extends ScheduledPollEndpoint {
     }
 
     public void setOssClient(OSSClient ossClient) {
-        this.ossClient = ossClient;
-        this.autowiredOssClient = ossClient != null;
+        lock.lock();
+        try {
+            this.ossClient = ossClient;
+            this.autowiredOssClient = ossClient != null;
+        } finally {
+            lock.unlock();
+        }
     }
 }
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSEndpointTest.java
 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSEndpointTest.java
index 252028abd92f..098918d91ea6 100644
--- 
a/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSEndpointTest.java
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSEndpointTest.java
@@ -16,10 +16,24 @@
  */
 package org.apache.camel.component.alibaba.oss;
 
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
 import com.aliyun.sdk.service.oss2.OSSClient;
 import org.junit.jupiter.api.Test;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
@@ -68,4 +82,64 @@ class OSSEndpointTest {
         verify(client).close();
         assertThat(endpoint.getOssClient()).isNull();
     }
+
+    @Test
+    void concurrentInitClientCreatesOneClient() throws Exception {
+        int callers = 8;
+        Set<Thread> creators = ConcurrentHashMap.newKeySet();
+        List<OSSClient> created = new CopyOnWriteArrayList<>();
+        CountDownLatch release = new CountDownLatch(1);
+        OSSEndpoint endpoint = new OSSEndpoint() {
+            @Override
+            OSSClient createClient() {
+                creators.add(Thread.currentThread());
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                OSSClient client = mock(OSSClient.class);
+                created.add(client);
+                return client;
+            }
+        };
+
+        Set<Thread> threads = ConcurrentHashMap.newKeySet();
+        ExecutorService executor = Executors.newFixedThreadPool(callers);
+        try {
+            List<Future<OSSClient>> results = new ArrayList<>();
+            for (int i = 0; i < callers; i++) {
+                results.add(executor.submit(() -> {
+                    threads.add(Thread.currentThread());
+                    return endpoint.initClient();
+                }));
+            }
+            // a creation is held until each caller has started one too, or 
waits for the lock of a caller that has,
+            // so the result does not depend on how the threads are scheduled
+            await().atMost(10, TimeUnit.SECONDS).until(() -> threads.size() == 
callers
+                    && threads.stream().allMatch(thread -> 
creators.contains(thread) || waitsForLockOf(thread, creators)));
+            release.countDown();
+
+            List<OSSClient> clients = new ArrayList<>();
+            for (Future<OSSClient> result : results) {
+                clients.add(result.get(10, TimeUnit.SECONDS));
+            }
+            assertThat(created).hasSize(1);
+            assertThat(clients).hasSize(callers).allSatisfy(client -> 
assertThat(client).isSameAs(created.get(0)));
+            assertThat(endpoint.getOssClient()).isSameAs(created.get(0));
+
+            endpoint.doStop();
+            verify(created.get(0)).close();
+            assertThat(endpoint.getOssClient()).isNull();
+        } finally {
+            release.countDown();
+            executor.shutdownNow();
+        }
+    }
+
+    private static boolean waitsForLockOf(Thread thread, Set<Thread> owners) {
+        ThreadInfo info = 
ManagementFactory.getThreadMXBean().getThreadInfo(thread.threadId());
+        return info != null && owners.stream().anyMatch(owner -> 
owner.threadId() == info.getLockOwnerId());
+    }
 }

Reply via email to