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 d04be35a4300 CAMEL-27533: camel-hazelcast - 
ReplicatedHazelcastAggregationRepository fails to start with optimistic=true, 
and the docs say when thread-safe mode is safe (#30824)
d04be35a4300 is described below

commit d04be35a430013f2af43e2b769e758c0c7cc6123
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 15:21:29 2026 +0530

    CAMEL-27533: camel-hazelcast - ReplicatedHazelcastAggregationRepository 
fails to start with optimistic=true, and the docs say when thread-safe mode is 
safe (#30824)
    
    ReplicatedMap extends java.util.Map, not ConcurrentMap, and Hazelcast's
    ReplicatedMapProxy does not override putIfAbsent, replace(key, old, new)
    or remove(key, value). With optimistic=true the repository used these
    java.util.Map default methods: a read of the local copy, an equals check,
    then a separate put or remove. The expected value is a newly marshalled
    DefaultExchangeHolder, which has no equals, so every update of a stored
    group and every completion of a stored group failed with
    OptimisticLockingException (retried forever with the default retry
    policy). When two members started the same group at the same time, both
    put; the second member threw only after its put had replaced the first
    member's group, whose message was acknowledged and lost.
    
    A ReplicatedMap has no atomic compare-and-set, so the repository now
    fails in doStart() with an IllegalArgumentException when optimistic is
    true, before it creates its own Hazelcast instance; the route that uses
    it fails to start. The only route that ran before with optimistic=true is
    one whose groups all complete on their first message (completionSize(1)),
    where the repository is never written; it now fails to start too, and
    runs again with optimistic=false. add(key, old, new) throws an
    UnsupportedOperationException that says the Aggregate EIP has
    optimisticLocking turned on, for a route that turns it on with the
    repository in thread-safe mode (it failed there before too, without a
    message). The unreachable optimistic branch of remove() is removed.
    Backing the mode with an IMap would make the class
    HazelcastAggregationRepository under another name, and adding equals to
    the holder would keep the check and the write in two steps on a copy that
    can lag the owner.
    
    Docs: a new section on the Hazelcast component page (and its catalog
    copy) and the class Javadoc of both repositories say that in thread-safe
    mode the cluster lock of the key is held only while a group is written,
    not while the Aggregate EIP reads and aggregates it, so only one
    aggregator should update a given correlation key at a time; two members
    aggregating the same key lose messages. Upgrade guide entry for 4.24.
    
    ReplicatedHazelcastAggregationRepositoryOptimisticTest runs on two
    embedded members: the repository and a route with optimistic=true fail
    to start, the thread-safe repository under optimisticLocking fails each
    message with the message, and a control shows one aggregator with four
    threads loses no message.
    
    * CAMEL-27533: camel-hazelcast - review follow-up: one ProducerTemplate per 
sender thread in the test
    
    - ReplicatedHazelcastAggregationRepositoryOptimisticTest: each sender 
thread creates one ProducerTemplate before the
      barrier and closes it after its loop, instead of a new template per 
message (200 that were never stopped); the
      template of the optimistic locking route test is closed too.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/hazelcast-summary.adoc      |  20 +++
 .../src/main/docs/hazelcast-summary.adoc           |  20 +++
 .../hazelcast/HazelcastAggregationRepository.java  |   4 +
 .../ReplicatedHazelcastAggregationRepository.java  | 133 +++++++-------
 ...zelcastAggregationRepositoryOptimisticTest.java | 191 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  14 ++
 6 files changed, 310 insertions(+), 72 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-summary.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-summary.adoc
index 8db9e561f2e6..7a08cac8fb09 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-summary.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hazelcast-summary.adoc
@@ -195,4 +195,24 @@ Java deserialization in the JVM, not only to Hazelcast.
 When Camel starts a Hazelcast member or client from a `Config` or 
`ClientConfig` you supplied that declares no
 filter, and no JVM-wide filter is set, it logs a WARN.
 
+== Aggregation repositories
+
+`camel-hazelcast` provides two aggregation repositories for the 
xref:eips:aggregate-eip.adoc[Aggregate] EIP:
+
+* `HazelcastAggregationRepository` keeps the groups and the completed 
exchanges in Hazelcast `IMap` maps.
+* `ReplicatedHazelcastAggregationRepository` keeps them in Hazelcast 
`ReplicatedMap` maps, which have a copy on every
+member, so each member reads them from its own copy.
+
+By default (`optimistic=false`), a repository holds a cluster-wide lock on the 
correlation key only while it writes a
+group. The Aggregate EIP reads the group, aggregates the new message into it, 
and writes it back, and only its own lock
+keeps the other threads of the same aggregator out of these steps. This is 
safe when one aggregator updates a given
+correlation key at a time, such as a route that runs on one member only. When 
the aggregators of two members (or two
+routes) update the same correlation key at the same time, one of them can 
overwrite the group that the other one just
+wrote, and the messages that the other one added are lost. This applies to 
both repositories.
+
+`ReplicatedHazelcastAggregationRepository` does not support optimistic 
locking: a `ReplicatedMap` has no atomic
+compare-and-set, so the repository fails to start with `optimistic=true`. A 
lock around the read would not make it safe
+for several aggregators either, as a member reads the group from its own copy, 
which can miss a write that another
+member has just made.
+
 
diff --git a/components/camel-hazelcast/src/main/docs/hazelcast-summary.adoc 
b/components/camel-hazelcast/src/main/docs/hazelcast-summary.adoc
index 8db9e561f2e6..7a08cac8fb09 100644
--- a/components/camel-hazelcast/src/main/docs/hazelcast-summary.adoc
+++ b/components/camel-hazelcast/src/main/docs/hazelcast-summary.adoc
@@ -195,4 +195,24 @@ Java deserialization in the JVM, not only to Hazelcast.
 When Camel starts a Hazelcast member or client from a `Config` or 
`ClientConfig` you supplied that declares no
 filter, and no JVM-wide filter is set, it logs a WARN.
 
+== Aggregation repositories
+
+`camel-hazelcast` provides two aggregation repositories for the 
xref:eips:aggregate-eip.adoc[Aggregate] EIP:
+
+* `HazelcastAggregationRepository` keeps the groups and the completed 
exchanges in Hazelcast `IMap` maps.
+* `ReplicatedHazelcastAggregationRepository` keeps them in Hazelcast 
`ReplicatedMap` maps, which have a copy on every
+member, so each member reads them from its own copy.
+
+By default (`optimistic=false`), a repository holds a cluster-wide lock on the 
correlation key only while it writes a
+group. The Aggregate EIP reads the group, aggregates the new message into it, 
and writes it back, and only its own lock
+keeps the other threads of the same aggregator out of these steps. This is 
safe when one aggregator updates a given
+correlation key at a time, such as a route that runs on one member only. When 
the aggregators of two members (or two
+routes) update the same correlation key at the same time, one of them can 
overwrite the group that the other one just
+wrote, and the messages that the other one added are lost. This applies to 
both repositories.
+
+`ReplicatedHazelcastAggregationRepository` does not support optimistic 
locking: a `ReplicatedMap` has no atomic
+compare-and-set, so the repository fails to start with `optimistic=true`. A 
lock around the read would not make it safe
+for several aggregators either, as a member reads the group from its own copy, 
which can miss a write that another
+member has just made.
+
 
diff --git 
a/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/HazelcastAggregationRepository.java
 
b/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/HazelcastAggregationRepository.java
index 53a347dbff03..252d9c2c118c 100644
--- 
a/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/HazelcastAggregationRepository.java
+++ 
b/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/HazelcastAggregationRepository.java
@@ -55,6 +55,10 @@ import org.slf4j.LoggerFactory;
  * are gained this way. If the {@link HazelcastAggregationRepository} uses 
it's own local {@link HazelcastInstance} it
  * will DESTROY this instance on {@link #doStop()}. You should control {@link 
HazelcastInstance} lifecycle yourself
  * whenever you instantiate {@link HazelcastAggregationRepository} passing a 
reference to the instance.
+ * <p>
+ * In thread-safe mode the cluster lock of the key is held only while a group 
is written, not while the Aggregate EIP
+ * reads the group and aggregates, so only one aggregator should update a 
given correlation key at a time: when two
+ * members aggregate the same key, one can overwrite the group that the other 
just wrote.
  */
 @Metadata(label = "bean",
           description = "Aggregation repository that uses Hazelcast Cache to 
store exchanges.",
diff --git 
a/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/ReplicatedHazelcastAggregationRepository.java
 
b/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/ReplicatedHazelcastAggregationRepository.java
index fc680be8492e..95d82f0a12bf 100644
--- 
a/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/ReplicatedHazelcastAggregationRepository.java
+++ 
b/components/camel-hazelcast/src/main/java/org/apache/camel/processor/aggregate/hazelcast/ReplicatedHazelcastAggregationRepository.java
@@ -38,18 +38,39 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * A Hazelcast-based AggregationRepository implementing {@link 
RecoverableAggregationRepository} and
- * {@link OptimisticLockingAggregationRepository}. Defaults to thread-safe 
(non-optimistic) locking and recoverable
- * strategy. Hazelcast settings are given to an end-user and can be controlled 
with repositoryName and
- * persistentRespositoryName, both are {@link com.hazelcast.map.IMap} 
&lt;String, Exchange&gt;. However
- * ReplicatedHazelcastAggregationRepository can run it's own Hazelcast 
instance, but obviously no benefits of Hazelcast
- * clustering are gained this way. If the {@link 
ReplicatedHazelcastAggregationRepository} uses it's own local
+ * A Hazelcast-based AggregationRepository implementing {@link 
RecoverableAggregationRepository}, which keeps the groups
+ * and the completed exchanges in {@link 
com.hazelcast.replicatedmap.ReplicatedMap}s named by repositoryName and
+ * persistentRepositoryName, so every member of the cluster reads them from 
its own copy. Uses thread-safe
+ * (non-optimistic) locking and defaults to recoverable strategy.
+ * <p>
+ * Optimistic locking is not supported, although the class inherits {@link 
OptimisticLockingAggregationRepository} from
+ * {@link HazelcastAggregationRepository}: a {@code ReplicatedMap} has no 
atomic compare-and-set (its
+ * {@code putIfAbsent}, {@code replace} and {@code remove(key, value)} are the 
{@link Map} default methods, a read of
+ * the local copy followed by a separate write), so the repository fails to 
start when {@code optimistic} is
+ * {@code true}.
+ * <p>
+ * In thread-safe mode, the Aggregate EIP reads the group, aggregates and 
writes it back, and only the write is done
+ * under the cluster lock of the key. Only one aggregator in the cluster 
should aggregate a given correlation key at a
+ * time: when two members aggregate the same key, a member can overwrite a 
group that the other member just updated, and
+ * the messages added by that update are lost. A lock around the read would 
not prevent it either, as the read is from
+ * the local copy, which can still miss a write of another member.
+ * <p>
+ * ReplicatedHazelcastAggregationRepository can run its own Hazelcast 
instance, but obviously no benefits of Hazelcast
+ * clustering are gained this way. If the {@link 
ReplicatedHazelcastAggregationRepository} uses its own local
  * {@link HazelcastInstance} it will DESTROY this instance on {@link 
#doStop()}. You should control
  * {@link HazelcastInstance} lifecycle yourself whenever you instantiate
  * {@link ReplicatedHazelcastAggregationRepository} passing a reference to the 
instance.
  */
 public class ReplicatedHazelcastAggregationRepository extends 
HazelcastAggregationRepository {
     private static final Logger LOG = 
LoggerFactory.getLogger(ReplicatedHazelcastAggregationRepository.class.getName());
+    static final String OPTIMISTIC_NOT_SUPPORTED
+            = "ReplicatedHazelcastAggregationRepository does not support 
optimistic locking (optimistic=true), as a Hazelcast"
+              + " ReplicatedMap has no atomic compare-and-set. Use it with 
optimistic=false, and without optimisticLocking on"
+              + " the Aggregate EIP.";
+    static final String OPTIMISTIC_LOCKING_NOT_SUPPORTED
+            = "ReplicatedHazelcastAggregationRepository does not support 
optimistic locking, as a Hazelcast ReplicatedMap"
+              + " has no atomic compare-and-set, but the Aggregate EIP has 
optimisticLocking turned on. Use the Aggregate"
+              + " EIP without optimisticLocking.";
     protected Map<String, DefaultExchangeHolder> replicatedCache;
     protected Map<String, DefaultExchangeHolder> replicatedPersistedCache;
     // IMap for distributed locking since ReplicatedMap doesn't support lock 
operations
@@ -85,7 +106,8 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
      * instance. Recoverable repository name defaults to {@code 
repositoryName} + "-compeleted".
      *
      * @param repositoryName {@link IMap} repository name;
-     * @param optimistic     whether to use optimistic locking manner.
+     * @param optimistic     must be {@code false}: optimistic locking is not 
supported, and the repository fails to
+     *                       start when it is {@code true}.
      */
     public ReplicatedHazelcastAggregationRepository(final String 
repositoryName, boolean optimistic) {
         super(repositoryName, optimistic);
@@ -97,7 +119,8 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
      *
      * @param repositoryName           {@link IMap} repository name;
      * @param persistentRepositoryName {@link IMap} recoverable repository 
name;
-     * @param optimistic               whether to use optimistic locking 
manner.
+     * @param optimistic               must be {@code false}: optimistic 
locking is not supported, and the repository
+     *                                 fails to start when it is {@code true}.
      */
     public ReplicatedHazelcastAggregationRepository(final String 
repositoryName, final String persistentRepositoryName,
                                                     boolean optimistic) {
@@ -133,7 +156,8 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
      * name defaults to {@code repositoryName} + "-compeleted".
      *
      * @param repositoryName {@link IMap} repository name;
-     * @param optimistic     whether to use optimistic locking manner;
+     * @param optimistic     must be {@code false}: optimistic locking is not 
supported, and the repository fails to
+     *                       start when it is {@code true};
      * @param hzInstance     externally configured {@link HazelcastInstance}.
      */
     public ReplicatedHazelcastAggregationRepository(final String 
repositoryName, boolean optimistic,
@@ -145,7 +169,8 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
      * Creates new {@link ReplicatedHazelcastAggregationRepository} with 
recoverable behavior.
      *
      * @param repositoryName           {@link IMap} repository name;
-     * @param optimistic               whether to use optimistic locking 
manner;
+     * @param optimistic               must be {@code false}: optimistic 
locking is not supported, and the repository
+     *                                 fails to start when it is {@code true};
      * @param persistentRepositoryName {@link IMap} recoverable repository 
name;
      * @param hzInstance               externally configured {@link 
HazelcastInstance}.
      */
@@ -154,35 +179,14 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
         super(repositoryName, persistentRepositoryName, optimistic, 
hzInstance);
     }
 
+    /**
+     * Not supported: optimistic locking needs an atomic compare-and-set, 
which a {@code ReplicatedMap} does not have.
+     *
+     * @throws UnsupportedOperationException always
+     */
     @Override
-    public Exchange add(CamelContext camelContext, String key, Exchange 
oldExchange, Exchange newExchange)
-            throws OptimisticLockingException {
-        if (!optimistic) {
-            throw new UnsupportedOperationException();
-        }
-        LOG.trace("Adding an Exchange with ID {} for key {} in an optimistic 
manner.", newExchange.getExchangeId(), key);
-        if (oldExchange == null) {
-            DefaultExchangeHolder holder = 
DefaultExchangeHolder.marshal(newExchange, true, allowSerializedHeaders);
-            final DefaultExchangeHolder misbehaviorHolder = 
replicatedCache.putIfAbsent(key, holder);
-            if (misbehaviorHolder != null) {
-                Exchange misbehaviorEx = unmarshallExchange(camelContext, 
misbehaviorHolder);
-                LOG.error(
-                        "Optimistic locking failed for exchange with key {}: 
IMap#putIfAbsend returned Exchange with ID {}, while it's expected no exchanges 
to be returned",
-                        key, misbehaviorEx != null ? 
misbehaviorEx.getExchangeId() : "<null>");
-                throw new OptimisticLockingException();
-            }
-        } else {
-            DefaultExchangeHolder oldHolder = 
DefaultExchangeHolder.marshal(oldExchange, true, allowSerializedHeaders);
-            DefaultExchangeHolder newHolder = 
DefaultExchangeHolder.marshal(newExchange, true, allowSerializedHeaders);
-            if (!replicatedCache.replace(key, oldHolder, newHolder)) {
-                LOG.error(
-                        "Optimistic locking failed for exchange with key {}: 
IMap#replace returned no Exchanges, while it's expected to replace one",
-                        key);
-                throw new OptimisticLockingException();
-            }
-        }
-        LOG.trace("Added an Exchange with ID {} for key {} in optimistic 
manner.", newExchange.getExchangeId(), key);
-        return oldExchange;
+    public Exchange add(CamelContext camelContext, String key, Exchange 
oldExchange, Exchange newExchange) {
+        throw new 
UnsupportedOperationException(OPTIMISTIC_LOCKING_NOT_SUPPORTED);
     }
 
     @Override
@@ -245,9 +249,9 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
     }
 
     /**
-     * This method performs transactional operation on removing the {@code 
exchange} from the operational storage and
-     * moving it into the persistent one if the {@link 
HazelcastAggregationRepository} runs in recoverable mode and
-     * {@code optimistic} is false. It will act at <u>your own</u> risk 
otherwise.
+     * Removes the group of the key. With recovery, the given exchange is 
first stored in the persistent map for
+     * recovery, under the cluster lock of the key that {@link 
#add(CamelContext, String, Exchange)} uses. A
+     * {@code ReplicatedMap} cannot take part in a Hazelcast transaction, so 
the two writes are not atomic.
      *
      * @param camelContext the current CamelContext
      * @param key          the correlation key
@@ -256,40 +260,22 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
     @Override
     public void remove(CamelContext camelContext, String key, Exchange 
exchange) {
         DefaultExchangeHolder holder = DefaultExchangeHolder.marshal(exchange, 
true, allowSerializedHeaders);
-        if (optimistic) {
-            LOG.trace("Removing an exchange with ID {} for key {} in an 
optimistic manner.", exchange.getExchangeId(), key);
-            if (!replicatedCache.remove(key, holder)) {
-                LOG.error(
-                        "Optimistic locking failed for exchange with key {}: 
IMap#remove removed no Exchanges, while it's expected to remove one.",
-                        key);
-                throw new OptimisticLockingException();
-            }
-            LOG.trace("Removed an exchange with ID {} for key {} in an 
optimistic manner.", exchange.getExchangeId(), key);
-            if (useRecovery) {
-                LOG.trace("Putting an exchange with ID {} for key {} into a 
recoverable storage in an optimistic manner.",
-                        exchange.getExchangeId(), key);
+        if (useRecovery) {
+            LOG.trace("Removing an exchange with ID {} for key {} in a 
thread-safe manner.", exchange.getExchangeId(), key);
+            // a ReplicatedMap cannot take part in a Hazelcast transaction, so 
the completed exchange is stored for
+            // recovery before the group is removed, under the lock that add() 
uses for the key.
+            // The given exchange is stored and not the removed entry: when a 
group is completed by an incoming
+            // exchange, the last aggregated exchange is not added to the 
repository before it is removed
+            lockMap.lock(key);
+            try {
                 replicatedPersistedCache.put(exchange.getExchangeId(), holder);
-                LOG.trace("Put an exchange with ID {} for key {} into a 
recoverable storage in an optimistic manner.",
-                        exchange.getExchangeId(), key);
-            }
-        } else {
-            if (useRecovery) {
-                LOG.trace("Removing an exchange with ID {} for key {} in a 
thread-safe manner.", exchange.getExchangeId(), key);
-                // a ReplicatedMap cannot take part in a Hazelcast 
transaction, so the completed exchange is stored for
-                // recovery before the group is removed, under the lock that 
add() uses for the key.
-                // The given exchange is stored and not the removed entry: 
when a group is completed by an incoming
-                // exchange, the last aggregated exchange is not added to the 
repository before it is removed
-                lockMap.lock(key);
-                try {
-                    replicatedPersistedCache.put(exchange.getExchangeId(), 
holder);
-                    replicatedCache.remove(key);
-                } finally {
-                    lockMap.unlock(key);
-                }
-                LOG.trace("Removed an exchange with ID {} for key {} in a 
thread-safe manner.", exchange.getExchangeId(), key);
-            } else {
                 replicatedCache.remove(key);
+            } finally {
+                lockMap.unlock(key);
             }
+            LOG.trace("Removed an exchange with ID {} for key {} in a 
thread-safe manner.", exchange.getExchangeId(), key);
+        } else {
+            replicatedCache.remove(key);
         }
     }
 
@@ -317,6 +303,9 @@ public class ReplicatedHazelcastAggregationRepository 
extends HazelcastAggregati
 
     @Override
     protected void doStart() throws Exception {
+        if (optimistic) {
+            throw new IllegalArgumentException(OPTIMISTIC_NOT_SUPPORTED);
+        }
         if (maximumRedeliveries < 0) {
             throw new IllegalArgumentException("Maximum redelivery retries 
must be zero or a positive integer.");
         }
diff --git 
a/components/camel-hazelcast/src/test/java/org/apache/camel/processor/aggregate/hazelcast/ReplicatedHazelcastAggregationRepositoryOptimisticTest.java
 
b/components/camel-hazelcast/src/test/java/org/apache/camel/processor/aggregate/hazelcast/ReplicatedHazelcastAggregationRepositoryOptimisticTest.java
new file mode 100644
index 000000000000..c5305e0dc1c1
--- /dev/null
+++ 
b/components/camel-hazelcast/src/test/java/org/apache/camel/processor/aggregate/hazelcast/ReplicatedHazelcastAggregationRepositoryOptimisticTest.java
@@ -0,0 +1,191 @@
+/*
+ * 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.processor.aggregate.hazelcast;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A {@link ReplicatedHazelcastAggregationRepository} cannot do optimistic 
locking (a ReplicatedMap has no atomic
+ * compare-and-set), so it refuses to start with {@code optimistic=true}. The 
last test is a control (it passes without
+ * the change too): in its thread-safe mode, with one aggregator per 
correlation key as the documentation says, no
+ * message is lost when several threads aggregate the same key.
+ */
+class ReplicatedHazelcastAggregationRepositoryOptimisticTest extends 
HazelcastAggregationRepositoryCamelTestSupport {
+
+    @Test
+    void optimisticRepositoryFailsToStart() {
+        ReplicatedHazelcastAggregationRepository repository
+                = new 
ReplicatedHazelcastAggregationRepository("replicatedOptimisticStart", true, 
getFirstInstance());
+        try {
+            IllegalArgumentException e = 
assertThrows(IllegalArgumentException.class, repository::start);
+            
assertEquals(ReplicatedHazelcastAggregationRepository.OPTIMISTIC_NOT_SUPPORTED, 
e.getMessage());
+        } finally {
+            repository.stop();
+        }
+    }
+
+    @Test
+    void optimisticRepositoryWithoutInstanceFailsToStart() {
+        ReplicatedHazelcastAggregationRepository repository
+                = new 
ReplicatedHazelcastAggregationRepository("replicatedOptimisticLocal", true);
+        try {
+            assertThrows(IllegalArgumentException.class, repository::start);
+            // the repository has no Hazelcast instance of its own left running
+            assertNull(repository.getHazelcastInstance());
+        } finally {
+            repository.stop();
+        }
+    }
+
+    @Test
+    void routeWithOptimisticRepositoryFailsToStart() throws Exception {
+        ReplicatedHazelcastAggregationRepository repository
+                = new 
ReplicatedHazelcastAggregationRepository("replicatedOptimisticRoute", true, 
getFirstInstance());
+        CamelContext camel = new DefaultCamelContext();
+        camel.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:in")
+                        .aggregate(header("id"), new 
SumOfIntsAggregationStrategy())
+                        .aggregationRepository(repository)
+                        .optimisticLocking()
+                        .completionSize(2)
+                        .to("mock:result");
+            }
+        });
+        try {
+            Exception e = assertThrows(Exception.class, camel::start);
+            assertTrue(hasCause(e, 
ReplicatedHazelcastAggregationRepository.OPTIMISTIC_NOT_SUPPORTED),
+                    "expected the cause to say optimistic locking is not 
supported, but was: " + e);
+        } finally {
+            camel.stop();
+        }
+    }
+
+    @Test
+    void optimisticLockingRouteWithThreadSafeRepositoryFailsWithAMessage() 
throws Exception {
+        ReplicatedHazelcastAggregationRepository repository
+                = new 
ReplicatedHazelcastAggregationRepository("replicatedThreadSafeRoute", false, 
getFirstInstance());
+        CamelContext camel = new DefaultCamelContext();
+        camel.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:in")
+                        .aggregate(header("id"), new 
SumOfIntsAggregationStrategy())
+                        .aggregationRepository(repository)
+                        .optimisticLocking()
+                        .completionSize(2)
+                        .to("mock:result");
+            }
+        });
+        camel.start();
+        try (ProducerTemplate template = camel.createProducerTemplate()) {
+            CamelExecutionException e = 
assertThrows(CamelExecutionException.class,
+                    () -> template.sendBodyAndHeader("direct:in", 1, "id", 
"g"));
+            UnsupportedOperationException cause = 
assertInstanceOf(UnsupportedOperationException.class, e.getCause());
+            
assertEquals(ReplicatedHazelcastAggregationRepository.OPTIMISTIC_LOCKING_NOT_SUPPORTED,
 cause.getMessage());
+            assertEquals(0, camel.getEndpoint("mock:result", 
MockEndpoint.class).getReceivedCounter());
+        } finally {
+            camel.stop();
+        }
+    }
+
+    @Test
+    void threadSafeRepositoryWithOneAggregatorLosesNoMessage() throws 
Exception {
+        int threads = 4;
+        int perThread = 50;
+        ReplicatedHazelcastAggregationRepository repository
+                = new 
ReplicatedHazelcastAggregationRepository("replicatedThreadSafeOneAggregator", 
getFirstInstance());
+        CamelContext camel = new DefaultCamelContext();
+        camel.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:in")
+                        .aggregate(header("id"), new 
SumOfIntsAggregationStrategy())
+                        .aggregationRepository(repository)
+                        .completionSize(threads * perThread)
+                        .to("mock:result");
+            }
+        });
+        camel.start();
+        try {
+            MockEndpoint mock = camel.getEndpoint("mock:result", 
MockEndpoint.class);
+            // exactly one aggregate, with every message of every thread
+            mock.expectedBodiesReceived(threads * perThread);
+            mock.setAssertPeriod(500);
+
+            CyclicBarrier barrier = new CyclicBarrier(threads);
+            AtomicReference<Exception> failure = new AtomicReference<>();
+            List<Thread> senders = new ArrayList<>();
+            for (int i = 0; i < threads; i++) {
+                Thread sender = new Thread(() -> send(camel, barrier, 
perThread, failure));
+                senders.add(sender);
+                sender.start();
+            }
+            for (Thread sender : senders) {
+                sender.join(TimeUnit.SECONDS.toMillis(30));
+                assertFalse(sender.isAlive());
+            }
+            assertNull(failure.get());
+
+            mock.assertIsSatisfied();
+            assertTrue(repository.getKeys().isEmpty());
+        } finally {
+            camel.stop();
+        }
+    }
+
+    private static void send(CamelContext camel, CyclicBarrier barrier, int 
count, AtomicReference<Exception> failure) {
+        // one template per sender thread, created before the threads start 
sending together
+        try (ProducerTemplate template = camel.createProducerTemplate()) {
+            barrier.await(10, TimeUnit.SECONDS);
+            for (int i = 0; i < count; i++) {
+                template.sendBodyAndHeader("direct:in", 1, "id", "g");
+            }
+        } catch (Exception e) {
+            failure.compareAndSet(null, e);
+        }
+    }
+
+    private static boolean hasCause(Throwable t, String message) {
+        for (Throwable c = t; c != null; c = c.getCause()) {
+            if (c instanceof IllegalArgumentException && 
message.equals(c.getMessage())) {
+                return true;
+            }
+        }
+        return false;
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 0845a308794d..909a40f2242a 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -5341,6 +5341,20 @@ cluster. The policy now releases the lock when the last 
route that uses it is re
 it competes for the lock again when a route that uses it is added again (with 
the same or a new policy instance). So a
 route reloaded on the leader can now move to another node.
 
+=== camel-hazelcast - ReplicatedHazelcastAggregationRepository fails to start 
with optimistic=true
+
+A `ReplicatedHazelcastAggregationRepository` created with `optimistic=true` 
could never add a message to a stored group,
+nor complete a stored group: every such update failed with an 
`OptimisticLockingException` and was tried again, forever
+with the default retry policy of the Aggregate EIP. When two members started 
the same group at the same time, the first
+message of one of them was lost. A Hazelcast `ReplicatedMap` has no atomic 
compare-and-set, so the repository now fails
+to start with `optimistic=true` (an `IllegalArgumentException`), and so does 
the route that uses it. The only route that
+ran before with `optimistic=true` is one whose groups all complete on their 
first message (for example
+`completionSize(1)`), where the repository is never written; such a route now 
fails to start too, and runs again with
+`optimistic=false`. Use the repository with `optimistic=false` and without 
`optimisticLocking` on the Aggregate EIP; the
+xref:components::hazelcast-summary.adoc[Hazelcast component] page says when 
that mode is safe. When the Aggregate EIP
+has `optimisticLocking` turned on and uses a 
`ReplicatedHazelcastAggregationRepository` with `optimistic=false`, each
+message still fails, as before, now with an `UnsupportedOperationException` 
that says so.
+
 === camel-sql, camel-mybatis, camel-jooq - an exchange marked rollback only 
last is not consumed either
 
 The SQL, MyBatis and jOOQ consumers already left a message unconsumed when the 
route marked the exchange rollback

Reply via email to