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 3e47dd3db451 CAMEL-27421: camel-alibaba - synchronize initClient 
across eventbridge, fc, kms, sls and sms (#30683)
3e47dd3db451 is described below

commit 3e47dd3db4510b3be00db5db7b1edb6d49b7dfa4
Author: Krish Mehta <[email protected]>
AuthorDate: Tue Nov 24 02:31:44 2026 +0530

    CAMEL-27421: camel-alibaba - synchronize initClient across eventbridge, fc, 
kms, sls and sms (#30683)
    
    Make the lazy creation of the client in the eventbridge, fc, kms, sls and 
sms endpoints thread safe, the same way as
    AlibabaOtsEndpoint: a volatile field, re-checked under the endpoint lock, 
with doStop() and the setters taking the
    same lock. The producers ask the endpoint for the client on each exchange 
instead of caching one of their own.
    
    Co-authored-by: Gemini <[email protected]>
---
 .../eventbridge/AlibabaEventBridgeEndpoint.java    |  41 +++++--
 .../eventbridge/AlibabaEventBridgeProducer.java    |  10 +-
 .../AlibabaEventBridgeEndpointTest.java            | 135 +++++++++++++++++++++
 .../AlibabaEventBridgeProducerTest.java            |  61 ++++++++++
 .../camel/component/alibaba/fc/FCEndpoint.java     |  41 +++++--
 .../camel/component/alibaba/fc/FCProducer.java     |  14 +--
 .../camel/component/alibaba/fc/FCEndpointTest.java | 135 +++++++++++++++++++++
 .../camel/component/alibaba/fc/FCProducerTest.java |  57 +++++++++
 .../camel/component/alibaba/kms/KMSEndpoint.java   |  41 +++++--
 .../camel/component/alibaba/kms/KMSProducer.java   |  18 ++-
 .../component/alibaba/kms/KMSEndpointTest.java     | 135 +++++++++++++++++++++
 .../component/alibaba/kms/KMSProducerTest.java     |  55 +++++++++
 .../component/alibaba/sls/AlibabaSlsEndpoint.java  |  45 +++++--
 .../alibaba/sls/AlibabaSlsEndpointTest.java        |  80 ++++++++++++
 .../camel/component/alibaba/sms/SMSEndpoint.java   |  41 +++++--
 .../camel/component/alibaba/sms/SMSProducer.java   |  10 +-
 .../component/alibaba/sms/SMSEndpointTest.java     | 135 +++++++++++++++++++++
 .../component/alibaba/sms/SMSProducerTest.java     |  57 +++++++++
 18 files changed, 1030 insertions(+), 81 deletions(-)

diff --git 
a/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeEndpoint.java
 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeEndpoint.java
index 9c64ac0d11a0..20ca45024130 100644
--- 
a/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeEndpoint.java
+++ 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeEndpoint.java
@@ -175,7 +175,7 @@ public class AlibabaEventBridgeEndpoint extends 
DefaultEndpoint {
                             + " these options. It creates this client when the 
producer processes its first message.",
               displayName = "EventBridge Client", label = "advanced")
     @Metadata(autowired = true)
-    private EventBridgeClient eventBridgeClient;
+    private volatile EventBridgeClient eventBridgeClient;
 
     private boolean autowiredEventBridgeClient;
     private EventSourceCache eventSourceCache;
@@ -199,11 +199,24 @@ public class AlibabaEventBridgeEndpoint extends 
DefaultEndpoint {
     }
 
     public EventBridgeClient initClient() {
-        if (eventBridgeClient != null) {
-            return eventBridgeClient;
+        EventBridgeClient answer = eventBridgeClient;
+        if (answer == null) {
+            lock.lock();
+            try {
+                answer = eventBridgeClient;
+                if (answer == null) {
+                    answer = createClient();
+                    eventBridgeClient = answer;
+                }
+            } finally {
+                lock.unlock();
+            }
         }
-        eventBridgeClient = AlibabaEventBridgeUtils.createClient(this);
-        return eventBridgeClient;
+        return answer;
+    }
+
+    EventBridgeClient createClient() {
+        return AlibabaEventBridgeUtils.createClient(this);
     }
 
     @Override
@@ -216,8 +229,13 @@ public class AlibabaEventBridgeEndpoint extends 
DefaultEndpoint {
 
     @Override
     protected void doStop() throws Exception {
-        if (eventBridgeClient != null && !autowiredEventBridgeClient) {
-            eventBridgeClient = null;
+        lock.lock();
+        try {
+            if (eventBridgeClient != null && !autowiredEventBridgeClient) {
+                eventBridgeClient = null;
+            }
+        } finally {
+            lock.unlock();
         }
         if (eventSourceCache != null) {
             eventSourceCache.clear();
@@ -359,7 +377,12 @@ public class AlibabaEventBridgeEndpoint extends 
DefaultEndpoint {
     }
 
     public void setEventBridgeClient(EventBridgeClient eventBridgeClient) {
-        this.eventBridgeClient = eventBridgeClient;
-        this.autowiredEventBridgeClient = eventBridgeClient != null;
+        lock.lock();
+        try {
+            this.eventBridgeClient = eventBridgeClient;
+            this.autowiredEventBridgeClient = eventBridgeClient != null;
+        } finally {
+            lock.unlock();
+        }
     }
 }
diff --git 
a/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeProducer.java
 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeProducer.java
index faf333b04a92..2ce91df15fe4 100644
--- 
a/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeProducer.java
+++ 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/main/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeProducer.java
@@ -30,8 +30,6 @@ import org.apache.camel.util.ObjectHelper;
 
 public class AlibabaEventBridgeProducer extends DefaultProducer {
 
-    private EventBridgeClient eventBridgeClient;
-
     public AlibabaEventBridgeProducer(AlibabaEventBridgeEndpoint endpoint) {
         super(endpoint);
     }
@@ -45,17 +43,15 @@ public class AlibabaEventBridgeProducer extends 
DefaultProducer {
             throw new IllegalArgumentException("Operation name not found");
         }
 
-        if (eventBridgeClient == null) {
-            eventBridgeClient = endpoint.initClient();
-        }
+        EventBridgeClient eventBridgeClient = endpoint.initClient();
 
         switch (configuration.operation()) {
-            case AlibabaEventBridgeOperations.PUT_EVENTS -> 
putEvents(exchange, configuration);
+            case AlibabaEventBridgeOperations.PUT_EVENTS -> 
putEvents(exchange, configuration, eventBridgeClient);
             default -> throw new UnsupportedOperationException("Unsupported 
operation: " + configuration.operation());
         }
     }
 
-    private void putEvents(Exchange exchange, ClientConfigurations 
configuration) {
+    private void putEvents(Exchange exchange, ClientConfigurations 
configuration, EventBridgeClient eventBridgeClient) {
         AlibabaEventBridgeEndpoint endpoint = getEndpoint();
         List<CloudEvent> events = AlibabaEventBridgeUtils.resolveCloudEvents(
                 exchange, configuration, endpoint.getEventSourceCache(), 
eventBridgeClient);
diff --git 
a/components/camel-alibaba/camel-alibaba-eventbridge/src/test/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeEndpointTest.java
 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/test/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeEndpointTest.java
new file mode 100644
index 000000000000..fe4b74a3a4ef
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/test/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeEndpointTest.java
@@ -0,0 +1,135 @@
+/*
+ * 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.alibaba.eventbridge;
+
+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.eventbridge.EventBridgeClient;
+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;
+
+class AlibabaEventBridgeEndpointTest {
+
+    @Test
+    void initClientReturnsCachedInstance() {
+        AlibabaEventBridgeEndpoint endpoint = new AlibabaEventBridgeEndpoint();
+        EventBridgeClient client = mock(EventBridgeClient.class);
+        endpoint.setEventBridgeClient(client);
+
+        EventBridgeClient first = endpoint.initClient();
+        EventBridgeClient second = endpoint.initClient();
+
+        assertThat(first).isSameAs(second).isSameAs(client);
+    }
+
+    @Test
+    void doStopKeepsAutowiredClient() throws Exception {
+        AlibabaEventBridgeEndpoint endpoint = new AlibabaEventBridgeEndpoint();
+        EventBridgeClient client = mock(EventBridgeClient.class);
+        endpoint.setEventBridgeClient(client);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getEventBridgeClient()).isSameAs(client);
+    }
+
+    @Test
+    void doStopClearsOwnedClient() throws Exception {
+        AlibabaEventBridgeEndpoint endpoint = new AlibabaEventBridgeEndpoint();
+        EventBridgeClient client = mock(EventBridgeClient.class);
+
+        var clientField = 
AlibabaEventBridgeEndpoint.class.getDeclaredField("eventBridgeClient");
+        clientField.setAccessible(true);
+        clientField.set(endpoint, client);
+
+        var autowiredField = 
AlibabaEventBridgeEndpoint.class.getDeclaredField("autowiredEventBridgeClient");
+        autowiredField.setAccessible(true);
+        autowiredField.setBoolean(endpoint, false);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getEventBridgeClient()).isNull();
+    }
+
+    @Test
+    void concurrentInitClientCreatesOneClient() throws Exception {
+        int callers = 8;
+        Set<Thread> creators = ConcurrentHashMap.newKeySet();
+        List<EventBridgeClient> created = new CopyOnWriteArrayList<>();
+        CountDownLatch release = new CountDownLatch(1);
+        AlibabaEventBridgeEndpoint endpoint = new AlibabaEventBridgeEndpoint() 
{
+            @Override
+            EventBridgeClient createClient() {
+                creators.add(Thread.currentThread());
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                EventBridgeClient client = mock(EventBridgeClient.class);
+                created.add(client);
+                return client;
+            }
+        };
+
+        Set<Thread> threads = ConcurrentHashMap.newKeySet();
+        ExecutorService executor = Executors.newFixedThreadPool(callers);
+        try {
+            List<Future<EventBridgeClient>> results = new ArrayList<>();
+            for (int i = 0; i < callers; i++) {
+                results.add(executor.submit(() -> {
+                    threads.add(Thread.currentThread());
+                    return endpoint.initClient();
+                }));
+            }
+            await().atMost(10, TimeUnit.SECONDS).until(() -> threads.size() == 
callers
+                    && threads.stream().allMatch(thread -> 
creators.contains(thread) || waitsForLockOf(thread, creators)));
+            release.countDown();
+
+            List<EventBridgeClient> clients = new ArrayList<>();
+            for (Future<EventBridgeClient> 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.getEventBridgeClient()).isSameAs(created.get(0));
+        } 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-eventbridge/src/test/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeProducerTest.java
 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/test/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeProducerTest.java
new file mode 100644
index 000000000000..f6d30f309d2a
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-eventbridge/src/test/java/org/apache/camel/component/alibaba/eventbridge/AlibabaEventBridgeProducerTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.alibaba.eventbridge;
+
+import com.aliyun.eventbridge.EventBridgeClient;
+import com.aliyun.eventbridge.models.PutEventsResponse;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class AlibabaEventBridgeProducerTest extends CamelTestSupport {
+
+    @Test
+    void processReinitializesClientFromEndpointOnEachExchange() throws 
Exception {
+        AlibabaEventBridgeEndpoint endpoint = 
mock(AlibabaEventBridgeEndpoint.class);
+        when(endpoint.getOperation()).thenReturn("putEvents");
+        when(endpoint.getEventBusName()).thenReturn("demo-bus");
+        when(endpoint.getEventSource()).thenReturn("demo-source");
+        when(endpoint.getEventType()).thenReturn("demo-type");
+        when(endpoint.getCamelContext()).thenReturn(context);
+
+        EventBridgeClient firstClient = mock(EventBridgeClient.class);
+        EventBridgeClient secondClient = mock(EventBridgeClient.class);
+        when(endpoint.initClient()).thenReturn(firstClient, secondClient);
+
+        PutEventsResponse response = new PutEventsResponse();
+        when(firstClient.putEvents(anyList())).thenReturn(response);
+        when(secondClient.putEvents(anyList())).thenReturn(response);
+
+        AlibabaEventBridgeProducer producer = new 
AlibabaEventBridgeProducer(endpoint);
+        var exchange1 = new DefaultExchange(context);
+        exchange1.getMessage().setBody("{\"key\":\"value1\"}");
+        producer.process(exchange1);
+
+        var exchange2 = new DefaultExchange(context);
+        exchange2.getMessage().setBody("{\"key\":\"value2\"}");
+        producer.process(exchange2);
+
+        verify(firstClient).putEvents(anyList());
+        verify(secondClient).putEvents(anyList());
+    }
+}
diff --git 
a/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCEndpoint.java
 
b/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCEndpoint.java
index 9bb9f93b6ee2..e5212f5d3dbd 100644
--- 
a/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCEndpoint.java
+++ 
b/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCEndpoint.java
@@ -120,7 +120,7 @@ public class FCEndpoint extends DefaultEndpoint {
                             + " creates this client when the producer 
processes its first message.",
               displayName = "FC Client", label = "advanced")
     @Metadata(autowired = true)
-    private Client fcClient;
+    private volatile Client fcClient;
 
     private boolean autowiredFcClient;
 
@@ -143,17 +143,35 @@ public class FCEndpoint extends DefaultEndpoint {
     }
 
     public Client initClient() throws Exception {
-        if (fcClient != null) {
-            return fcClient;
+        Client answer = fcClient;
+        if (answer == null) {
+            lock.lock();
+            try {
+                answer = fcClient;
+                if (answer == null) {
+                    answer = createClient();
+                    fcClient = answer;
+                }
+            } finally {
+                lock.unlock();
+            }
         }
-        fcClient = FCUtils.createClient(this);
-        return fcClient;
+        return answer;
+    }
+
+    Client createClient() throws Exception {
+        return FCUtils.createClient(this);
     }
 
     @Override
     protected void doStop() throws Exception {
-        if (fcClient != null && !autowiredFcClient) {
-            fcClient = null;
+        lock.lock();
+        try {
+            if (fcClient != null && !autowiredFcClient) {
+                fcClient = null;
+            }
+        } finally {
+            lock.unlock();
         }
         super.doStop();
     }
@@ -243,7 +261,12 @@ public class FCEndpoint extends DefaultEndpoint {
     }
 
     public void setFcClient(Client fcClient) {
-        this.fcClient = fcClient;
-        this.autowiredFcClient = fcClient != null;
+        lock.lock();
+        try {
+            this.fcClient = fcClient;
+            this.autowiredFcClient = fcClient != null;
+        } finally {
+            lock.unlock();
+        }
     }
 }
diff --git 
a/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCProducer.java
 
b/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCProducer.java
index b3548c0f5858..91c14cd8a8f1 100644
--- 
a/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCProducer.java
+++ 
b/components/camel-alibaba/camel-alibaba-fc/src/main/java/org/apache/camel/component/alibaba/fc/FCProducer.java
@@ -30,8 +30,6 @@ import org.apache.camel.util.ObjectHelper;
 
 public class FCProducer extends DefaultProducer {
 
-    private Client fcClient;
-
     public FCProducer(FCEndpoint endpoint) {
         super(endpoint);
     }
@@ -45,18 +43,16 @@ public class FCProducer extends DefaultProducer {
             throw new IllegalArgumentException("Operation name not found");
         }
 
-        if (fcClient == null) {
-            fcClient = endpoint.initClient();
-        }
+        Client fcClient = endpoint.initClient();
 
         switch (configuration.operation()) {
-            case FCOperations.INVOKE_FUNCTION -> invokeFunction(exchange, 
configuration);
-            case FCOperations.GET_FUNCTION -> getFunction(exchange, 
configuration);
+            case FCOperations.INVOKE_FUNCTION -> invokeFunction(exchange, 
configuration, fcClient);
+            case FCOperations.GET_FUNCTION -> getFunction(exchange, 
configuration, fcClient);
             default -> throw new UnsupportedOperationException("Unsupported 
operation: " + configuration.operation());
         }
     }
 
-    private void invokeFunction(Exchange exchange, ClientConfigurations 
configuration) throws Exception {
+    private void invokeFunction(Exchange exchange, ClientConfigurations 
configuration, Client fcClient) throws Exception {
         validateServiceAndFunction(configuration);
 
         InvokeFunctionRequest request = new InvokeFunctionRequest()
@@ -79,7 +75,7 @@ public class FCProducer extends DefaultProducer {
         }
     }
 
-    private void getFunction(Exchange exchange, ClientConfigurations 
configuration) throws Exception {
+    private void getFunction(Exchange exchange, ClientConfigurations 
configuration, Client fcClient) throws Exception {
         validateServiceAndFunction(configuration);
 
         GetFunctionRequest request = new GetFunctionRequest();
diff --git 
a/components/camel-alibaba/camel-alibaba-fc/src/test/java/org/apache/camel/component/alibaba/fc/FCEndpointTest.java
 
b/components/camel-alibaba/camel-alibaba-fc/src/test/java/org/apache/camel/component/alibaba/fc/FCEndpointTest.java
new file mode 100644
index 000000000000..0cfb452b3348
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-fc/src/test/java/org/apache/camel/component/alibaba/fc/FCEndpointTest.java
@@ -0,0 +1,135 @@
+/*
+ * 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.alibaba.fc;
+
+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.fc_open20210406.Client;
+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;
+
+class FCEndpointTest {
+
+    @Test
+    void initClientReturnsCachedInstance() throws Exception {
+        FCEndpoint endpoint = new FCEndpoint();
+        Client client = mock(Client.class);
+        endpoint.setFcClient(client);
+
+        Client first = endpoint.initClient();
+        Client second = endpoint.initClient();
+
+        assertThat(first).isSameAs(second).isSameAs(client);
+    }
+
+    @Test
+    void doStopKeepsAutowiredClient() throws Exception {
+        FCEndpoint endpoint = new FCEndpoint();
+        Client client = mock(Client.class);
+        endpoint.setFcClient(client);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getFcClient()).isSameAs(client);
+    }
+
+    @Test
+    void doStopClearsOwnedClient() throws Exception {
+        FCEndpoint endpoint = new FCEndpoint();
+        Client client = mock(Client.class);
+
+        var clientField = FCEndpoint.class.getDeclaredField("fcClient");
+        clientField.setAccessible(true);
+        clientField.set(endpoint, client);
+
+        var autowiredField = 
FCEndpoint.class.getDeclaredField("autowiredFcClient");
+        autowiredField.setAccessible(true);
+        autowiredField.setBoolean(endpoint, false);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getFcClient()).isNull();
+    }
+
+    @Test
+    void concurrentInitClientCreatesOneClient() throws Exception {
+        int callers = 8;
+        Set<Thread> creators = ConcurrentHashMap.newKeySet();
+        List<Client> created = new CopyOnWriteArrayList<>();
+        CountDownLatch release = new CountDownLatch(1);
+        FCEndpoint endpoint = new FCEndpoint() {
+            @Override
+            Client createClient() {
+                creators.add(Thread.currentThread());
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                Client client = mock(Client.class);
+                created.add(client);
+                return client;
+            }
+        };
+
+        Set<Thread> threads = ConcurrentHashMap.newKeySet();
+        ExecutorService executor = Executors.newFixedThreadPool(callers);
+        try {
+            List<Future<Client>> results = new ArrayList<>();
+            for (int i = 0; i < callers; i++) {
+                results.add(executor.submit(() -> {
+                    threads.add(Thread.currentThread());
+                    return endpoint.initClient();
+                }));
+            }
+            await().atMost(10, TimeUnit.SECONDS).until(() -> threads.size() == 
callers
+                    && threads.stream().allMatch(thread -> 
creators.contains(thread) || waitsForLockOf(thread, creators)));
+            release.countDown();
+
+            List<Client> clients = new ArrayList<>();
+            for (Future<Client> 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.getFcClient()).isSameAs(created.get(0));
+        } 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-fc/src/test/java/org/apache/camel/component/alibaba/fc/FCProducerTest.java
 
b/components/camel-alibaba/camel-alibaba-fc/src/test/java/org/apache/camel/component/alibaba/fc/FCProducerTest.java
new file mode 100644
index 000000000000..6d4a4e77141b
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-fc/src/test/java/org/apache/camel/component/alibaba/fc/FCProducerTest.java
@@ -0,0 +1,57 @@
+/*
+ * 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.alibaba.fc;
+
+import com.aliyun.fc_open20210406.Client;
+import com.aliyun.fc_open20210406.models.GetFunctionRequest;
+import com.aliyun.fc_open20210406.models.GetFunctionResponse;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class FCProducerTest extends CamelTestSupport {
+
+    @Test
+    void processReinitializesClientFromEndpointOnEachExchange() throws 
Exception {
+        FCEndpoint endpoint = mock(FCEndpoint.class);
+        when(endpoint.getOperation()).thenReturn("getFunction");
+        when(endpoint.getServiceName()).thenReturn("demo-service");
+        when(endpoint.getFunctionName()).thenReturn("demo-func");
+        when(endpoint.getCamelContext()).thenReturn(context);
+
+        Client firstClient = mock(Client.class);
+        Client secondClient = mock(Client.class);
+        when(endpoint.initClient()).thenReturn(firstClient, secondClient);
+
+        GetFunctionResponse response = new GetFunctionResponse();
+        when(firstClient.getFunction(eq("demo-service"), eq("demo-func"), 
any(GetFunctionRequest.class))).thenReturn(response);
+        when(secondClient.getFunction(eq("demo-service"), eq("demo-func"), 
any(GetFunctionRequest.class))).thenReturn(response);
+
+        FCProducer producer = new FCProducer(endpoint);
+        producer.process(new DefaultExchange(context));
+        producer.process(new DefaultExchange(context));
+
+        verify(firstClient).getFunction(eq("demo-service"), eq("demo-func"), 
any(GetFunctionRequest.class));
+        verify(secondClient).getFunction(eq("demo-service"), eq("demo-func"), 
any(GetFunctionRequest.class));
+    }
+}
diff --git 
a/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSEndpoint.java
 
b/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSEndpoint.java
index e61f85e6049a..c13fb8618377 100644
--- 
a/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSEndpoint.java
+++ 
b/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSEndpoint.java
@@ -139,7 +139,7 @@ public class KMSEndpoint extends DefaultEndpoint {
                             + " this client when the producer processes its 
first message.",
               displayName = "KMS Client", label = "advanced")
     @Metadata(autowired = true)
-    private Client kmsClient;
+    private volatile Client kmsClient;
 
     private boolean autowiredKmsClient;
 
@@ -162,17 +162,35 @@ public class KMSEndpoint extends DefaultEndpoint {
     }
 
     public Client initClient() throws Exception {
-        if (kmsClient != null) {
-            return kmsClient;
+        Client answer = kmsClient;
+        if (answer == null) {
+            lock.lock();
+            try {
+                answer = kmsClient;
+                if (answer == null) {
+                    answer = createClient();
+                    kmsClient = answer;
+                }
+            } finally {
+                lock.unlock();
+            }
         }
-        kmsClient = KMSUtils.createClient(this);
-        return kmsClient;
+        return answer;
+    }
+
+    Client createClient() throws Exception {
+        return KMSUtils.createClient(this);
     }
 
     @Override
     protected void doStop() throws Exception {
-        if (kmsClient != null && !autowiredKmsClient) {
-            kmsClient = null;
+        lock.lock();
+        try {
+            if (kmsClient != null && !autowiredKmsClient) {
+                kmsClient = null;
+            }
+        } finally {
+            lock.unlock();
         }
         super.doStop();
     }
@@ -270,7 +288,12 @@ public class KMSEndpoint extends DefaultEndpoint {
     }
 
     public void setKmsClient(Client kmsClient) {
-        this.kmsClient = kmsClient;
-        this.autowiredKmsClient = kmsClient != null;
+        lock.lock();
+        try {
+            this.kmsClient = kmsClient;
+            this.autowiredKmsClient = kmsClient != null;
+        } finally {
+            lock.unlock();
+        }
     }
 }
diff --git 
a/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSProducer.java
 
b/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSProducer.java
index ce74cd807b87..56a78b717500 100644
--- 
a/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSProducer.java
+++ 
b/components/camel-alibaba/camel-alibaba-kms/src/main/java/org/apache/camel/component/alibaba/kms/KMSProducer.java
@@ -29,8 +29,6 @@ import org.apache.camel.util.ObjectHelper;
 
 public class KMSProducer extends DefaultProducer {
 
-    private Client kmsClient;
-
     public KMSProducer(KMSEndpoint endpoint) {
         super(endpoint);
     }
@@ -44,19 +42,17 @@ public class KMSProducer extends DefaultProducer {
             throw new IllegalArgumentException("Operation name not found");
         }
 
-        if (kmsClient == null) {
-            kmsClient = endpoint.initClient();
-        }
+        Client kmsClient = endpoint.initClient();
 
         switch (configuration.operation()) {
-            case KMSOperations.ENCRYPT -> encrypt(exchange, configuration);
-            case KMSOperations.DECRYPT -> decrypt(exchange, configuration);
-            case KMSOperations.GENERATE_DATA_KEY -> generateDataKey(exchange, 
configuration);
+            case KMSOperations.ENCRYPT -> encrypt(exchange, configuration, 
kmsClient);
+            case KMSOperations.DECRYPT -> decrypt(exchange, configuration, 
kmsClient);
+            case KMSOperations.GENERATE_DATA_KEY -> generateDataKey(exchange, 
configuration, kmsClient);
             default -> throw new UnsupportedOperationException("Unsupported 
operation: " + configuration.operation());
         }
     }
 
-    private void encrypt(Exchange exchange, ClientConfigurations 
configuration) throws Exception {
+    private void encrypt(Exchange exchange, ClientConfigurations 
configuration, Client kmsClient) throws Exception {
         if (ObjectHelper.isEmpty(configuration.keyId())) {
             throw new IllegalArgumentException("Key id is required for 
encrypt");
         }
@@ -74,7 +70,7 @@ public class KMSProducer extends DefaultProducer {
         setRequestId(exchange, response.getBody() != null ? 
response.getBody().getRequestId() : null);
     }
 
-    private void decrypt(Exchange exchange, ClientConfigurations 
configuration) throws Exception {
+    private void decrypt(Exchange exchange, ClientConfigurations 
configuration, Client kmsClient) throws Exception {
         String ciphertextBlob = configuration.ciphertextBlob();
         if (ObjectHelper.isEmpty(ciphertextBlob)) {
             ciphertextBlob = exchange.getMessage().getBody(String.class);
@@ -88,7 +84,7 @@ public class KMSProducer extends DefaultProducer {
         setRequestId(exchange, response.getBody() != null ? 
response.getBody().getRequestId() : null);
     }
 
-    private void generateDataKey(Exchange exchange, ClientConfigurations 
configuration) throws Exception {
+    private void generateDataKey(Exchange exchange, ClientConfigurations 
configuration, Client kmsClient) throws Exception {
         if (ObjectHelper.isEmpty(configuration.keyId())) {
             throw new IllegalArgumentException("Key id is required for 
generateDataKey");
         }
diff --git 
a/components/camel-alibaba/camel-alibaba-kms/src/test/java/org/apache/camel/component/alibaba/kms/KMSEndpointTest.java
 
b/components/camel-alibaba/camel-alibaba-kms/src/test/java/org/apache/camel/component/alibaba/kms/KMSEndpointTest.java
new file mode 100644
index 000000000000..cd3bfc0e61ed
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-kms/src/test/java/org/apache/camel/component/alibaba/kms/KMSEndpointTest.java
@@ -0,0 +1,135 @@
+/*
+ * 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.alibaba.kms;
+
+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.kms20160120.Client;
+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;
+
+class KMSEndpointTest {
+
+    @Test
+    void initClientReturnsCachedInstance() throws Exception {
+        KMSEndpoint endpoint = new KMSEndpoint();
+        Client client = mock(Client.class);
+        endpoint.setKmsClient(client);
+
+        Client first = endpoint.initClient();
+        Client second = endpoint.initClient();
+
+        assertThat(first).isSameAs(second).isSameAs(client);
+    }
+
+    @Test
+    void doStopKeepsAutowiredClient() throws Exception {
+        KMSEndpoint endpoint = new KMSEndpoint();
+        Client client = mock(Client.class);
+        endpoint.setKmsClient(client);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getKmsClient()).isSameAs(client);
+    }
+
+    @Test
+    void doStopClearsOwnedClient() throws Exception {
+        KMSEndpoint endpoint = new KMSEndpoint();
+        Client client = mock(Client.class);
+
+        var clientField = KMSEndpoint.class.getDeclaredField("kmsClient");
+        clientField.setAccessible(true);
+        clientField.set(endpoint, client);
+
+        var autowiredField = 
KMSEndpoint.class.getDeclaredField("autowiredKmsClient");
+        autowiredField.setAccessible(true);
+        autowiredField.setBoolean(endpoint, false);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getKmsClient()).isNull();
+    }
+
+    @Test
+    void concurrentInitClientCreatesOneClient() throws Exception {
+        int callers = 8;
+        Set<Thread> creators = ConcurrentHashMap.newKeySet();
+        List<Client> created = new CopyOnWriteArrayList<>();
+        CountDownLatch release = new CountDownLatch(1);
+        KMSEndpoint endpoint = new KMSEndpoint() {
+            @Override
+            Client createClient() {
+                creators.add(Thread.currentThread());
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                Client client = mock(Client.class);
+                created.add(client);
+                return client;
+            }
+        };
+
+        Set<Thread> threads = ConcurrentHashMap.newKeySet();
+        ExecutorService executor = Executors.newFixedThreadPool(callers);
+        try {
+            List<Future<Client>> results = new ArrayList<>();
+            for (int i = 0; i < callers; i++) {
+                results.add(executor.submit(() -> {
+                    threads.add(Thread.currentThread());
+                    return endpoint.initClient();
+                }));
+            }
+            await().atMost(10, TimeUnit.SECONDS).until(() -> threads.size() == 
callers
+                    && threads.stream().allMatch(thread -> 
creators.contains(thread) || waitsForLockOf(thread, creators)));
+            release.countDown();
+
+            List<Client> clients = new ArrayList<>();
+            for (Future<Client> 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.getKmsClient()).isSameAs(created.get(0));
+        } 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-kms/src/test/java/org/apache/camel/component/alibaba/kms/KMSProducerTest.java
 
b/components/camel-alibaba/camel-alibaba-kms/src/test/java/org/apache/camel/component/alibaba/kms/KMSProducerTest.java
new file mode 100644
index 000000000000..b654c325dfbd
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-kms/src/test/java/org/apache/camel/component/alibaba/kms/KMSProducerTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.alibaba.kms;
+
+import com.aliyun.kms20160120.Client;
+import com.aliyun.kms20160120.models.GenerateDataKeyRequest;
+import com.aliyun.kms20160120.models.GenerateDataKeyResponse;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class KMSProducerTest extends CamelTestSupport {
+
+    @Test
+    void processReinitializesClientFromEndpointOnEachExchange() throws 
Exception {
+        KMSEndpoint endpoint = mock(KMSEndpoint.class);
+        when(endpoint.getOperation()).thenReturn("generateDataKey");
+        when(endpoint.getKeyId()).thenReturn("demo-key");
+        when(endpoint.getCamelContext()).thenReturn(context);
+
+        Client firstClient = mock(Client.class);
+        Client secondClient = mock(Client.class);
+        when(endpoint.initClient()).thenReturn(firstClient, secondClient);
+
+        GenerateDataKeyResponse response = new GenerateDataKeyResponse();
+        
when(firstClient.generateDataKey(any(GenerateDataKeyRequest.class))).thenReturn(response);
+        
when(secondClient.generateDataKey(any(GenerateDataKeyRequest.class))).thenReturn(response);
+
+        KMSProducer producer = new KMSProducer(endpoint);
+        producer.process(new DefaultExchange(context));
+        producer.process(new DefaultExchange(context));
+
+        verify(firstClient).generateDataKey(any(GenerateDataKeyRequest.class));
+        
verify(secondClient).generateDataKey(any(GenerateDataKeyRequest.class));
+    }
+}
diff --git 
a/components/camel-alibaba/camel-alibaba-sls/src/main/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpoint.java
 
b/components/camel-alibaba/camel-alibaba-sls/src/main/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpoint.java
index fb22162b3531..cb84dbbd25a8 100644
--- 
a/components/camel-alibaba/camel-alibaba-sls/src/main/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpoint.java
+++ 
b/components/camel-alibaba/camel-alibaba-sls/src/main/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpoint.java
@@ -172,7 +172,7 @@ public class AlibabaSlsEndpoint extends DefaultEndpoint {
                             + " options. It creates this client when the 
producer processes its first message.",
               displayName = "SLS Client", label = "advanced")
     @Metadata(autowired = true)
-    private Client slsClient;
+    private volatile Client slsClient;
 
     private boolean autowiredSlsClient;
 
@@ -195,19 +195,37 @@ public class AlibabaSlsEndpoint extends DefaultEndpoint {
     }
 
     public Client initClient() throws Exception {
-        if (slsClient != null) {
-            return slsClient;
+        Client answer = slsClient;
+        if (answer == null) {
+            lock.lock();
+            try {
+                answer = slsClient;
+                if (answer == null) {
+                    answer = createClient();
+                    slsClient = answer;
+                }
+            } finally {
+                lock.unlock();
+            }
         }
-        slsClient = AlibabaSlsUtils.createClient(this);
-        return slsClient;
+        return answer;
+    }
+
+    Client createClient() throws Exception {
+        return AlibabaSlsUtils.createClient(this);
     }
 
     @Override
     protected void doStop() throws Exception {
-        if (slsClient != null && !autowiredSlsClient) {
-            // com.aliyun.sls20201230.Client extends 
com.aliyun.teaopenapi.Client, which has no
-            // close/shutdown lifecycle API (same as camel-alibaba-eventbridge)
-            slsClient = null;
+        lock.lock();
+        try {
+            if (slsClient != null && !autowiredSlsClient) {
+                // com.aliyun.sls20201230.Client extends 
com.aliyun.teaopenapi.Client, which has no
+                // close/shutdown lifecycle API (same as 
camel-alibaba-eventbridge)
+                slsClient = null;
+            }
+        } finally {
+            lock.unlock();
         }
         super.doStop();
     }
@@ -337,7 +355,12 @@ public class AlibabaSlsEndpoint extends DefaultEndpoint {
     }
 
     public void setSlsClient(Client slsClient) {
-        this.slsClient = slsClient;
-        this.autowiredSlsClient = slsClient != null;
+        lock.lock();
+        try {
+            this.slsClient = slsClient;
+            this.autowiredSlsClient = slsClient != null;
+        } finally {
+            lock.unlock();
+        }
     }
 }
diff --git 
a/components/camel-alibaba/camel-alibaba-sls/src/test/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpointTest.java
 
b/components/camel-alibaba/camel-alibaba-sls/src/test/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpointTest.java
index 09a60440f3db..e061fd3ae0e5 100644
--- 
a/components/camel-alibaba/camel-alibaba-sls/src/test/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpointTest.java
+++ 
b/components/camel-alibaba/camel-alibaba-sls/src/test/java/org/apache/camel/component/alibaba/sls/AlibabaSlsEndpointTest.java
@@ -16,14 +16,40 @@
  */
 package org.apache.camel.component.alibaba.sls;
 
+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.sls20201230.Client;
 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;
 
 class AlibabaSlsEndpointTest {
 
+    @Test
+    void initClientReturnsCachedInstance() throws Exception {
+        AlibabaSlsEndpoint endpoint = new AlibabaSlsEndpoint();
+        Client client = mock(Client.class);
+        endpoint.setSlsClient(client);
+
+        Client first = endpoint.initClient();
+        Client second = endpoint.initClient();
+
+        assertThat(first).isSameAs(second).isSameAs(client);
+    }
+
     @Test
     void doStopKeepsAutowiredClient() throws Exception {
         AlibabaSlsEndpoint endpoint = new AlibabaSlsEndpoint();
@@ -52,4 +78,58 @@ class AlibabaSlsEndpointTest {
 
         assertThat(endpoint.getSlsClient()).isNull();
     }
+
+    @Test
+    void concurrentInitClientCreatesOneClient() throws Exception {
+        int callers = 8;
+        Set<Thread> creators = ConcurrentHashMap.newKeySet();
+        List<Client> created = new CopyOnWriteArrayList<>();
+        CountDownLatch release = new CountDownLatch(1);
+        AlibabaSlsEndpoint endpoint = new AlibabaSlsEndpoint() {
+            @Override
+            Client createClient() {
+                creators.add(Thread.currentThread());
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                Client client = mock(Client.class);
+                created.add(client);
+                return client;
+            }
+        };
+
+        Set<Thread> threads = ConcurrentHashMap.newKeySet();
+        ExecutorService executor = Executors.newFixedThreadPool(callers);
+        try {
+            List<Future<Client>> results = new ArrayList<>();
+            for (int i = 0; i < callers; i++) {
+                results.add(executor.submit(() -> {
+                    threads.add(Thread.currentThread());
+                    return endpoint.initClient();
+                }));
+            }
+            await().atMost(10, TimeUnit.SECONDS).until(() -> threads.size() == 
callers
+                    && threads.stream().allMatch(thread -> 
creators.contains(thread) || waitsForLockOf(thread, creators)));
+            release.countDown();
+
+            List<Client> clients = new ArrayList<>();
+            for (Future<Client> 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.getSlsClient()).isSameAs(created.get(0));
+        } 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-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSEndpoint.java
 
b/components/camel-alibaba/camel-alibaba-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSEndpoint.java
index 2ba2daca536a..b97888c18d58 100644
--- 
a/components/camel-alibaba/camel-alibaba-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSEndpoint.java
+++ 
b/components/camel-alibaba/camel-alibaba-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSEndpoint.java
@@ -128,7 +128,7 @@ public class SMSEndpoint extends DefaultEndpoint {
                             + " creates this client when the producer 
processes its first message.",
               displayName = "SMS Client", label = "advanced")
     @Metadata(autowired = true)
-    private Client smsClient;
+    private volatile Client smsClient;
 
     private boolean autowiredSmsClient;
 
@@ -151,17 +151,35 @@ public class SMSEndpoint extends DefaultEndpoint {
     }
 
     public Client initClient() throws Exception {
-        if (smsClient != null) {
-            return smsClient;
+        Client answer = smsClient;
+        if (answer == null) {
+            lock.lock();
+            try {
+                answer = smsClient;
+                if (answer == null) {
+                    answer = createClient();
+                    smsClient = answer;
+                }
+            } finally {
+                lock.unlock();
+            }
         }
-        smsClient = SMSUtils.createClient(this);
-        return smsClient;
+        return answer;
+    }
+
+    Client createClient() throws Exception {
+        return SMSUtils.createClient(this);
     }
 
     @Override
     protected void doStop() throws Exception {
-        if (smsClient != null && !autowiredSmsClient) {
-            smsClient = null;
+        lock.lock();
+        try {
+            if (smsClient != null && !autowiredSmsClient) {
+                smsClient = null;
+            }
+        } finally {
+            lock.unlock();
         }
         super.doStop();
     }
@@ -259,7 +277,12 @@ public class SMSEndpoint extends DefaultEndpoint {
     }
 
     public void setSmsClient(Client smsClient) {
-        this.smsClient = smsClient;
-        this.autowiredSmsClient = smsClient != null;
+        lock.lock();
+        try {
+            this.smsClient = smsClient;
+            this.autowiredSmsClient = smsClient != null;
+        } finally {
+            lock.unlock();
+        }
     }
 }
diff --git 
a/components/camel-alibaba/camel-alibaba-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSProducer.java
 
b/components/camel-alibaba/camel-alibaba-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSProducer.java
index d71c46e136fa..338ac5b265b2 100644
--- 
a/components/camel-alibaba/camel-alibaba-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSProducer.java
+++ 
b/components/camel-alibaba/camel-alibaba-sms/src/main/java/org/apache/camel/component/alibaba/sms/SMSProducer.java
@@ -28,8 +28,6 @@ import org.apache.camel.util.ObjectHelper;
 
 public class SMSProducer extends DefaultProducer {
 
-    private Client smsClient;
-
     public SMSProducer(SMSEndpoint endpoint) {
         super(endpoint);
     }
@@ -43,17 +41,15 @@ public class SMSProducer extends DefaultProducer {
             throw new IllegalArgumentException("Operation name not found");
         }
 
-        if (smsClient == null) {
-            smsClient = endpoint.initClient();
-        }
+        Client smsClient = endpoint.initClient();
 
         switch (configuration.operation()) {
-            case SMSOperations.SEND_SMS -> sendSms(exchange, configuration);
+            case SMSOperations.SEND_SMS -> sendSms(exchange, configuration, 
smsClient);
             default -> throw new UnsupportedOperationException("Unsupported 
operation: " + configuration.operation());
         }
     }
 
-    private void sendSms(Exchange exchange, ClientConfigurations 
configuration) throws Exception {
+    private void sendSms(Exchange exchange, ClientConfigurations 
configuration, Client smsClient) throws Exception {
         if (ObjectHelper.isEmpty(configuration.phoneNumbers())
                 || ObjectHelper.isEmpty(configuration.signName())
                 || ObjectHelper.isEmpty(configuration.templateCode())) {
diff --git 
a/components/camel-alibaba/camel-alibaba-sms/src/test/java/org/apache/camel/component/alibaba/sms/SMSEndpointTest.java
 
b/components/camel-alibaba/camel-alibaba-sms/src/test/java/org/apache/camel/component/alibaba/sms/SMSEndpointTest.java
new file mode 100644
index 000000000000..b33a9d8ad998
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-sms/src/test/java/org/apache/camel/component/alibaba/sms/SMSEndpointTest.java
@@ -0,0 +1,135 @@
+/*
+ * 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.alibaba.sms;
+
+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.dysmsapi20170525.Client;
+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;
+
+class SMSEndpointTest {
+
+    @Test
+    void initClientReturnsCachedInstance() throws Exception {
+        SMSEndpoint endpoint = new SMSEndpoint();
+        Client client = mock(Client.class);
+        endpoint.setSmsClient(client);
+
+        Client first = endpoint.initClient();
+        Client second = endpoint.initClient();
+
+        assertThat(first).isSameAs(second).isSameAs(client);
+    }
+
+    @Test
+    void doStopKeepsAutowiredClient() throws Exception {
+        SMSEndpoint endpoint = new SMSEndpoint();
+        Client client = mock(Client.class);
+        endpoint.setSmsClient(client);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getSmsClient()).isSameAs(client);
+    }
+
+    @Test
+    void doStopClearsOwnedClient() throws Exception {
+        SMSEndpoint endpoint = new SMSEndpoint();
+        Client client = mock(Client.class);
+
+        var clientField = SMSEndpoint.class.getDeclaredField("smsClient");
+        clientField.setAccessible(true);
+        clientField.set(endpoint, client);
+
+        var autowiredField = 
SMSEndpoint.class.getDeclaredField("autowiredSmsClient");
+        autowiredField.setAccessible(true);
+        autowiredField.setBoolean(endpoint, false);
+
+        endpoint.doStop();
+
+        assertThat(endpoint.getSmsClient()).isNull();
+    }
+
+    @Test
+    void concurrentInitClientCreatesOneClient() throws Exception {
+        int callers = 8;
+        Set<Thread> creators = ConcurrentHashMap.newKeySet();
+        List<Client> created = new CopyOnWriteArrayList<>();
+        CountDownLatch release = new CountDownLatch(1);
+        SMSEndpoint endpoint = new SMSEndpoint() {
+            @Override
+            Client createClient() {
+                creators.add(Thread.currentThread());
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalStateException(e);
+                }
+                Client client = mock(Client.class);
+                created.add(client);
+                return client;
+            }
+        };
+
+        Set<Thread> threads = ConcurrentHashMap.newKeySet();
+        ExecutorService executor = Executors.newFixedThreadPool(callers);
+        try {
+            List<Future<Client>> results = new ArrayList<>();
+            for (int i = 0; i < callers; i++) {
+                results.add(executor.submit(() -> {
+                    threads.add(Thread.currentThread());
+                    return endpoint.initClient();
+                }));
+            }
+            await().atMost(10, TimeUnit.SECONDS).until(() -> threads.size() == 
callers
+                    && threads.stream().allMatch(thread -> 
creators.contains(thread) || waitsForLockOf(thread, creators)));
+            release.countDown();
+
+            List<Client> clients = new ArrayList<>();
+            for (Future<Client> 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.getSmsClient()).isSameAs(created.get(0));
+        } 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-sms/src/test/java/org/apache/camel/component/alibaba/sms/SMSProducerTest.java
 
b/components/camel-alibaba/camel-alibaba-sms/src/test/java/org/apache/camel/component/alibaba/sms/SMSProducerTest.java
new file mode 100644
index 000000000000..24c874faa826
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-sms/src/test/java/org/apache/camel/component/alibaba/sms/SMSProducerTest.java
@@ -0,0 +1,57 @@
+/*
+ * 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.alibaba.sms;
+
+import com.aliyun.dysmsapi20170525.Client;
+import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
+import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class SMSProducerTest extends CamelTestSupport {
+
+    @Test
+    void processReinitializesClientFromEndpointOnEachExchange() throws 
Exception {
+        SMSEndpoint endpoint = mock(SMSEndpoint.class);
+        when(endpoint.getOperation()).thenReturn("sendSms");
+        when(endpoint.getPhoneNumbers()).thenReturn("13800138000");
+        when(endpoint.getSignName()).thenReturn("demo-sign");
+        when(endpoint.getTemplateCode()).thenReturn("SMS_123456");
+        when(endpoint.getCamelContext()).thenReturn(context);
+
+        Client firstClient = mock(Client.class);
+        Client secondClient = mock(Client.class);
+        when(endpoint.initClient()).thenReturn(firstClient, secondClient);
+
+        SendSmsResponse response = new SendSmsResponse();
+        
when(firstClient.sendSms(any(SendSmsRequest.class))).thenReturn(response);
+        
when(secondClient.sendSms(any(SendSmsRequest.class))).thenReturn(response);
+
+        SMSProducer producer = new SMSProducer(endpoint);
+        producer.process(new DefaultExchange(context));
+        producer.process(new DefaultExchange(context));
+
+        verify(firstClient).sendSms(any(SendSmsRequest.class));
+        verify(secondClient).sendSms(any(SendSmsRequest.class));
+    }
+}

Reply via email to