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

lizhimins pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/rocketmq.git


The following commit(s) were added to refs/heads/develop by this push:
     new 74c2a8e80a [ISSUE #11537] fix(client): fix hold-size leaks, stranded 
messages and lock-bound sync sends in ProduceAccumulator (#11538)
74c2a8e80a is described below

commit 74c2a8e80a5f5ce367ba06daa19fcc187e3416c4
Author: Lei Zhiyuan <[email protected]>
AuthorDate: Wed Nov 25 16:03:03 2026 +0800

    [ISSUE #11537] fix(client): fix hold-size leaks, stranded messages and 
lock-bound sync sends in ProduceAccumulator (#11538)
    
    * fix(client): avoid blocking and hold-size leaks in ProduceAccumulator
    
    - Sync add() no longer holds the batch monitor while sending or waiting;
      waiters use a per-batch latch with a holdMs timeout and send on expiry
      instead of relying on the guard thread to notify them.
    - A message already enqueued is no longer stranded when the caller is
      interrupted; the thread waits for the batch and restores the interrupt.
    - Send failures are propagated to every caller in the sync batch instead
      of surfacing as NullPointerException.
    - The sync guard thread no longer blocks on a slow batch's monitor.
    - tryAddMessage uses CAS instead of a global synchronized block.
    - Hold size is reserved only after the message is validated and known to
      be batchable, so delayed/retry/invalid messages no longer leak it.
    - Async send releases hold size exactly once, including when sendDirect
      throws synchronously.
    
    * refactor(client): simplify ProduceAccumulator batch lifecycle
    
    - Each batch completes a single CompletableFuture; hold size is released
      and callbacks are dispatched once from its completion handler, so the
      latch, exception field and release-once guard are gone.
    - Sync callers wait on their own result and send on hold-time expiry, so
      GuardForSyncSendService is removed.
    - A batch removes itself from its map when closed, so sent batches are no
      longer retained per aggregate key.
    - A throwing user callback no longer prevents other callbacks in the same
      batch from receiving their result.
    - Collapse the four send entry points into two and make AggregateKey
      immutable.
    - Tests use package-private accessors instead of reflection and share a
      configurable fake producer.
    
    * perf(client): let only the first caller of a sync batch time the hold 
delay
    
    Every sync caller used to wait with a timeout, so each one registered its
    own timer. With tens of thousands of concurrent (virtual thread) callers
    the shared timer queue became the bottleneck: 50k virtual threads over 3
    queues reached only ~0.2M msg/s with p50 ~250ms.
    
    Now only the caller that opened a batch waits with the hold timeout and
    sends on expiry; callers joining an existing batch wait untimed. The
    batch is still sent exactly once when it is full or its hold time
    expires.
    
    Mock-producer benchmark, 50k virtual threads, 3 queues:
    - JDK 21: 1ms send 0.18-0.23M -> 3.4M msg/s, p50 210-280ms -> 14ms;
              20ms send 0.2M -> 2.4M msg/s, p50 250ms -> 20.6ms
    - JDK 25: 1ms send 1.7M -> 3.7M msg/s; 20ms send 0.95-1.1M -> 2.3M msg/s,
              p50 44-50ms -> 20.6ms
    Platform-thread results (8/32/64 threads) are unchanged.
    
    * fix(client): do not fail a batch when the sending caller is interrupted
    
    The previous handling only cleared an interrupt that was already pending
    when the batch send started. If the sending caller was interrupted while
    sendDirect waited for the broker, that InterruptedException failed the
    whole batch, including messages of other callers.
    
    DefaultMQProducer#sendBatchDirect now retries the batch send once when it
    is interrupted, then restores the interrupt status. The batch is still
    sent exactly as a normal sync send, with the same retry configuration.
    A second interrupt is not retried: the batch fails with
    InterruptedException, as it does today.
    
    The trade-off is at-least-once: the first attempt may have reached the
    broker, so that message can be stored twice. This matches the documented
    semantics of DefaultMQProducer#send, which may also deliver duplicates
    when it retries.
    
    Test: testSyncSend_batchSendIsNotAbortedByCallerInterrupt interrupts the
    caller that sends a two-message batch and asserts that the other message
    still gets its own result and the interrupt status is restored.
---
 .../client/producer/DefaultMQProducer.java         |  49 +-
 .../client/producer/ProduceAccumulator.java        | 490 ++++++++------------
 .../client/producer/DefaultMQProducerTest.java     |  34 ++
 .../client/producer/ProduceAccumulatorTest.java    | 509 ++++++++++++++++-----
 4 files changed, 669 insertions(+), 413 deletions(-)

diff --git 
a/client/src/main/java/org/apache/rocketmq/client/producer/DefaultMQProducer.java
 
b/client/src/main/java/org/apache/rocketmq/client/producer/DefaultMQProducer.java
index 2091bbabbf..da9690614e 100644
--- 
a/client/src/main/java/org/apache/rocketmq/client/producer/DefaultMQProducer.java
+++ 
b/client/src/main/java/org/apache/rocketmq/client/producer/DefaultMQProducer.java
@@ -432,10 +432,6 @@ public class DefaultMQProducer extends ClientConfig 
implements MQProducer {
     }
 
     private boolean canBatch(Message msg) {
-        // produceAccumulator is full
-        if (!produceAccumulator.tryAddMessage(msg)) {
-            return false;
-        }
         // delay message do not support batch processing
         if (msg.getDelayTimeLevel() > 0 || msg.getDelayTimeMs() > 0 || 
msg.getDelayTimeSec() > 0 || msg.getDeliverTimeMs() > 0) {
             return false;
@@ -775,21 +771,48 @@ public class DefaultMQProducer extends ClientConfig 
implements MQProducer {
         }
     }
 
+    /**
+     * Sends one auto-batch message as a shared {@link ProduceAccumulator} 
batch and returns this message's own result.
+     * The batch belongs to the accumulator rather than to this caller, so 
interrupting this thread must not fail the
+     * other messages in the same batch. The interrupt status is restored when 
the call returns.
+     */
+    SendResult sendBatchDirect(Message msg, MessageQueue mq)
+        throws MQClientException, RemotingException, MQBrokerException, 
InterruptedException {
+        boolean interrupted = false;
+        try {
+            try {
+                return sendDirect(msg, mq, null);
+            } catch (InterruptedException e) {
+                // the batch send was interrupted before it completed, so send 
it again once instead of failing the
+                // messages of the other callers in the same batch
+                interrupted = true;
+            }
+            return sendDirect(msg, mq, null);
+        } finally {
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+        }
+    }
+
     public SendResult sendByAccumulator(Message msg, MessageQueue mq,
         SendCallback sendCallback) throws MQClientException, 
RemotingException, InterruptedException, MQBrokerException {
         // check whether it can batch
         if (!canBatch(msg)) {
             return sendDirect(msg, mq, sendCallback);
-        } else {
-            Validators.checkMessage(msg, this);
-            MessageClientIDSetter.setUniqID(msg);
-            if (sendCallback == null) {
-                return this.produceAccumulator.send(msg, mq, this);
-            } else {
-                this.produceAccumulator.send(msg, mq, sendCallback, this);
-                return null;
-            }
         }
+        // validate before reserving hold size, otherwise the reserved size 
would never be released
+        Validators.checkMessage(msg, this);
+        // produceAccumulator is full
+        if (!produceAccumulator.tryAddMessage(msg)) {
+            return sendDirect(msg, mq, sendCallback);
+        }
+        MessageClientIDSetter.setUniqID(msg);
+        if (sendCallback == null) {
+            return this.produceAccumulator.send(msg, mq, this);
+        }
+        this.produceAccumulator.send(msg, mq, sendCallback, this);
+        return null;
     }
 
     /**
diff --git 
a/client/src/main/java/org/apache/rocketmq/client/producer/ProduceAccumulator.java
 
b/client/src/main/java/org/apache/rocketmq/client/producer/ProduceAccumulator.java
index 809830e464..8c80d8ac9f 100644
--- 
a/client/src/main/java/org/apache/rocketmq/client/producer/ProduceAccumulator.java
+++ 
b/client/src/main/java/org/apache/rocketmq/client/producer/ProduceAccumulator.java
@@ -17,17 +17,20 @@
 
 package org.apache.rocketmq.client.producer;
 
+import com.google.common.base.Throwables;
+import com.google.common.util.concurrent.Uninterruptibles;
+import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
+import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicLong;
 import org.apache.rocketmq.client.exception.MQBrokerException;
 import org.apache.rocketmq.client.exception.MQClientException;
@@ -50,7 +53,6 @@ public class ProduceAccumulator {
     // holdMs normal value
     private int holdMs = 10;
     private final Logger log = 
LoggerFactory.getLogger(DefaultMQProducer.class);
-    private final GuardForSyncSendService guardThreadForSyncSend;
     private final GuardForAsyncSendService guardThreadForAsyncSend;
     private final Map<AggregateKey, MessageAccumulation> syncSendBatchs = new 
ConcurrentHashMap<AggregateKey, MessageAccumulation>();
     private final Map<AggregateKey, MessageAccumulation> asyncSendBatchs = new 
ConcurrentHashMap<AggregateKey, MessageAccumulation>();
@@ -59,57 +61,13 @@ public class ProduceAccumulator {
 
     public ProduceAccumulator(String instanceName) {
         this.instanceName = instanceName;
-        this.guardThreadForSyncSend = new 
GuardForSyncSendService(this.instanceName);
         this.guardThreadForAsyncSend = new 
GuardForAsyncSendService(this.instanceName);
     }
 
-    private class GuardForSyncSendService extends ServiceThread {
-        private final String serviceName;
-
-        public GuardForSyncSendService(String clientInstanceName) {
-            serviceName = String.format("Client_%s_GuardForSyncSend", 
clientInstanceName);
-        }
-
-        @Override
-        public String getServiceName() {
-            return serviceName;
-        }
-
-        @Override
-        public void run() {
-            log.info(this.getServiceName() + " service started");
-
-            while (!this.isStopped()) {
-                try {
-                    this.doWork();
-                } catch (Exception e) {
-                    log.warn(this.getServiceName() + " service has exception. 
", e);
-                }
-            }
-
-            log.info(this.getServiceName() + " service end");
-        }
-
-        private void doWork() throws InterruptedException {
-            Collection<MessageAccumulation> values = syncSendBatchs.values();
-            final int sleepTime = Math.max(1, holdMs / 2);
-            for (MessageAccumulation v : values) {
-                v.wakeup();
-                synchronized (v) {
-                    synchronized (v.closed) {
-                        if (v.messagesSize.get() == 0) {
-                            v.closed.set(true);
-                            syncSendBatchs.remove(v.aggregateKey, v);
-                        } else {
-                            v.notify();
-                        }
-                    }
-                }
-            }
-            Thread.sleep(sleepTime);
-        }
-    }
-
+    /**
+     * Sends async batches whose hold time has expired. Sync batches need no 
guard: their callers wait for the hold
+     * time themselves and send the batch on expiry.
+     */
     private class GuardForAsyncSendService extends ServiceThread {
         private final String serviceName;
 
@@ -137,31 +95,21 @@ public class ProduceAccumulator {
             log.info(this.getServiceName() + " service end");
         }
 
-        private void doWork() throws Exception {
-            Collection<MessageAccumulation> values = asyncSendBatchs.values();
-            final int sleepTime = Math.max(1, holdMs / 2);
-            for (MessageAccumulation v : values) {
+        private void doWork() throws InterruptedException {
+            for (MessageAccumulation v : asyncSendBatchs.values()) {
                 if (v.readyToSend()) {
-                    v.send(null);
-                }
-                synchronized (v.closed) {
-                    if (v.messagesSize.get() == 0) {
-                        v.closed.set(true);
-                        asyncSendBatchs.remove(v.aggregateKey, v);
-                    }
+                    v.send();
                 }
             }
-            Thread.sleep(sleepTime);
+            Thread.sleep(Math.max(1, holdMs / 2));
         }
     }
 
     void start() {
-        guardThreadForSyncSend.start();
         guardThreadForAsyncSend.start();
     }
 
     void shutdown() {
-        guardThreadForSyncSend.shutdown();
         guardThreadForAsyncSend.shutdown();
     }
 
@@ -198,118 +146,105 @@ public class ProduceAccumulator {
         this.totalHoldSize = totalHoldSize;
     }
 
-    private MessageAccumulation getOrCreateSyncSendBatch(AggregateKey 
aggregateKey,
-        DefaultMQProducer defaultMQProducer) {
-        MessageAccumulation batch = syncSendBatchs.get(aggregateKey);
-        if (batch != null) {
-            return batch;
+    SendResult send(Message msg, MessageQueue mq,
+        DefaultMQProducer defaultMQProducer) throws InterruptedException, 
MQBrokerException, RemotingException, MQClientException {
+        CompletableFuture<SendResult> result = new CompletableFuture<>();
+        MessageAccumulation batch = addToBatch(syncSendBatchs, false, msg, mq, 
completing(result), defaultMQProducer);
+        try {
+            // Only the batch's first caller times the hold delay; the rest 
wait untimed. A timed wait per caller
+            // registers one timer each, which dominates under many concurrent 
(e.g. virtual thread) callers.
+            if (batch != null) {
+                try {
+                    return Uninterruptibles.getUninterruptibly(result, 
batch.remainingHoldMs(), TimeUnit.MILLISECONDS);
+                } catch (TimeoutException e) {
+                    batch.send();
+                }
+            }
+            return Uninterruptibles.getUninterruptibly(result);
+        } catch (ExecutionException e) {
+            Throwable cause = e.getCause();
+            Throwables.throwIfInstanceOf(cause, MQBrokerException.class);
+            Throwables.throwIfInstanceOf(cause, RemotingException.class);
+            Throwables.throwIfInstanceOf(cause, MQClientException.class);
+            Throwables.throwIfInstanceOf(cause, InterruptedException.class);
+            Throwables.throwIfUnchecked(cause);
+            throw new MQClientException("send message batch failed", cause);
         }
-        batch = new MessageAccumulation(aggregateKey, defaultMQProducer);
-        MessageAccumulation previous = 
syncSendBatchs.putIfAbsent(aggregateKey, batch);
-
-        return previous == null ? batch : previous;
     }
 
-    private MessageAccumulation getOrCreateAsyncSendBatch(AggregateKey 
aggregateKey,
-        DefaultMQProducer defaultMQProducer) {
-        MessageAccumulation batch = asyncSendBatchs.get(aggregateKey);
-        if (batch != null) {
-            return batch;
-        }
-        batch = new MessageAccumulation(aggregateKey, defaultMQProducer);
-        MessageAccumulation previous = 
asyncSendBatchs.putIfAbsent(aggregateKey, batch);
-
-        return previous == null ? batch : previous;
+    void send(Message msg, MessageQueue mq, SendCallback sendCallback, 
DefaultMQProducer defaultMQProducer) {
+        addToBatch(asyncSendBatchs, true, msg, mq, sendCallback, 
defaultMQProducer);
     }
 
-    SendResult send(Message msg,
-        DefaultMQProducer defaultMQProducer) throws InterruptedException, 
MQBrokerException, RemotingException, MQClientException {
-        AggregateKey partitionKey = new AggregateKey(msg);
+    /**
+     * @return the batch if this message opened it, otherwise null
+     */
+    private MessageAccumulation addToBatch(Map<AggregateKey, 
MessageAccumulation> batches, boolean asyncSend,
+        Message msg, MessageQueue mq, SendCallback sendCallback, 
DefaultMQProducer defaultMQProducer) {
+        AggregateKey aggregateKey = new AggregateKey(msg, mq);
         while (true) {
-            MessageAccumulation batch = getOrCreateSyncSendBatch(partitionKey, 
defaultMQProducer);
-            int index = batch.add(msg);
-            if (index == -1) {
-                syncSendBatchs.remove(partitionKey, batch);
-            } else {
-                return batch.sendResults[index];
+            MessageAccumulation batch = batches.get(aggregateKey);
+            if (batch == null) {
+                MessageAccumulation created = new 
MessageAccumulation(aggregateKey, batches, asyncSend, defaultMQProducer);
+                batch = batches.putIfAbsent(aggregateKey, created);
+                if (batch == null) {
+                    batch = created;
+                }
             }
-        }
-    }
-
-    SendResult send(Message msg, MessageQueue mq,
-        DefaultMQProducer defaultMQProducer) throws InterruptedException, 
MQBrokerException, RemotingException, MQClientException {
-        AggregateKey partitionKey = new AggregateKey(msg, mq);
-        while (true) {
-            MessageAccumulation batch = getOrCreateSyncSendBatch(partitionKey, 
defaultMQProducer);
-            int index = batch.add(msg);
-            if (index == -1) {
-                syncSendBatchs.remove(partitionKey, batch);
-            } else {
-                return batch.sendResults[index];
+            // a closed batch has already removed itself from the map, so the 
retry picks up a fresh one
+            AddResult added = batch.add(msg, sendCallback);
+            if (added != AddResult.REJECTED) {
+                return added == AddResult.OPENED ? batch : null;
             }
         }
     }
 
-    void send(Message msg, SendCallback sendCallback,
-        DefaultMQProducer defaultMQProducer) throws InterruptedException, 
RemotingException, MQClientException {
-        AggregateKey partitionKey = new AggregateKey(msg);
-        while (true) {
-            MessageAccumulation batch = 
getOrCreateAsyncSendBatch(partitionKey, defaultMQProducer);
-            if (!batch.add(msg, sendCallback)) {
-                asyncSendBatchs.remove(partitionKey, batch);
-            } else {
-                return;
+    private static SendCallback completing(final CompletableFuture<SendResult> 
future) {
+        return new SendCallback() {
+            @Override
+            public void onSuccess(SendResult sendResult) {
+                future.complete(sendResult);
             }
-        }
-    }
 
-    void send(Message msg, MessageQueue mq,
-        SendCallback sendCallback,
-        DefaultMQProducer defaultMQProducer) throws InterruptedException, 
RemotingException, MQClientException {
-        AggregateKey partitionKey = new AggregateKey(msg, mq);
-        while (true) {
-            MessageAccumulation batch = 
getOrCreateAsyncSendBatch(partitionKey, defaultMQProducer);
-            if (!batch.add(msg, sendCallback)) {
-                asyncSendBatchs.remove(partitionKey, batch);
-            } else {
-                return;
+            @Override
+            public void onException(Throwable e) {
+                future.completeExceptionally(e);
             }
-        }
+        };
     }
 
     boolean tryAddMessage(Message message) {
-        synchronized (currentlyHoldSize) {
-            if (currentlyHoldSize.get() < totalHoldSize) {
-                int bodySize = null == message.getBody() ? 0 : 
message.getBody().length;
-                if (bodySize > 0) {
-                    currentlyHoldSize.addAndGet(bodySize);
-                }
-                return true;
-            } else {
+        int bodySize = null == message.getBody() ? 0 : 
message.getBody().length;
+        while (true) {
+            long current = currentlyHoldSize.get();
+            if (current >= totalHoldSize) {
                 return false;
             }
+            if (bodySize <= 0 || currentlyHoldSize.compareAndSet(current, 
current + bodySize)) {
+                return true;
+            }
         }
     }
 
-    private class AggregateKey {
-        public String topic = null;
-        public MessageQueue mq = null;
-        public boolean waitStoreMsgOK = false;
-        public String tag = null;
+    long getCurrentlyHoldSize() {
+        return currentlyHoldSize.get();
+    }
 
-        public AggregateKey(Message message) {
-            this(message.getTopic(), null, message.isWaitStoreMsgOK(), 
message.getTags());
-        }
+    int pendingBatchCount() {
+        return syncSendBatchs.size() + asyncSendBatchs.size();
+    }
 
-        public AggregateKey(Message message, MessageQueue mq) {
-            this(message.getTopic(), mq, message.isWaitStoreMsgOK(), 
message.getTags());
-        }
+    private static class AggregateKey {
+        private final String topic;
+        private final MessageQueue mq;
+        private final boolean waitStoreMsgOK;
+        private final String tag;
 
-        public AggregateKey(String topic, MessageQueue mq, boolean 
waitStoreMsgOK, String tag) {
-            this.topic = topic;
+        AggregateKey(Message message, MessageQueue mq) {
+            this.topic = message.getTopic();
             this.mq = mq;
-            this.waitStoreMsgOK = waitStoreMsgOK;
-            this.tag = tag;
+            this.waitStoreMsgOK = message.isWaitStoreMsgOK();
+            this.tag = message.getTags();
         }
 
         @Override
@@ -328,94 +263,121 @@ public class ProduceAccumulator {
         }
     }
 
+    private enum AddResult {
+        /** the message is the first of the batch */
+        OPENED,
+        /** the message joined a batch that already had messages */
+        JOINED,
+        /** the batch is closed and the message was not added */
+        REJECTED
+    }
+
+    /**
+     * One batch of messages sharing an {@link AggregateKey}. Lifecycle: open 
(accepting messages) -> closed (removed
+     * from its map and handed to sendDirect exactly once) -> completed 
({@link #sent} resolved, hold size released and
+     * each message's callback invoked in add order).
+     */
     private class MessageAccumulation {
+        private final AggregateKey aggregateKey;
+        private final Map<AggregateKey, MessageAccumulation> batches;
+        private final boolean asyncSend;
         private final DefaultMQProducer defaultMQProducer;
-        private LinkedList<Message> messages;
-        private LinkedList<SendCallback> sendCallbacks;
-        private Set<String> keys;
-        private final AtomicBoolean closed;
-        private SendResult[] sendResults;
-        private AggregateKey aggregateKey;
-        private AtomicInteger messagesSize;
-        private int count;
-        private long createTime;
-
-        public MessageAccumulation(AggregateKey aggregateKey, 
DefaultMQProducer defaultMQProducer) {
-            this.defaultMQProducer = defaultMQProducer;
-            this.messages = new LinkedList<Message>();
-            this.sendCallbacks = new LinkedList<SendCallback>();
-            this.keys = new HashSet<String>();
-            this.closed = new AtomicBoolean(false);
-            this.messagesSize = new AtomicInteger(0);
+        private final long createTime = System.currentTimeMillis();
+        private final CompletableFuture<SendResult> sent = new 
CompletableFuture<>();
+        // guarded by this; frozen once closed
+        private final List<Message> messages = new ArrayList<>();
+        private final List<SendCallback> sendCallbacks = new ArrayList<>();
+        private final Set<String> keys = new HashSet<>();
+        private long messagesSize;
+        private boolean closed;
+
+        MessageAccumulation(AggregateKey aggregateKey, Map<AggregateKey, 
MessageAccumulation> batches,
+            boolean asyncSend, DefaultMQProducer defaultMQProducer) {
             this.aggregateKey = aggregateKey;
-            this.count = 0;
-            this.createTime = System.currentTimeMillis();
+            this.batches = batches;
+            this.asyncSend = asyncSend;
+            this.defaultMQProducer = defaultMQProducer;
+            this.sent.whenComplete(this::complete);
         }
 
-        private boolean readyToSend() {
-            if (this.messagesSize.get() > holdSize
-                || System.currentTimeMillis() >= this.createTime + holdMs) {
-                return true;
-            }
-            return false;
+        synchronized boolean readyToSend() {
+            return !messages.isEmpty() && (messagesSize > holdSize || 
remainingHoldMs() <= 0);
         }
 
-        public int add(Message msg) throws InterruptedException, 
MQBrokerException, RemotingException, MQClientException {
-            int ret = -1;
-            synchronized (this.closed) {
-                if (this.closed.get()) {
-                    return ret;
-                }
-                ret = this.count++;
-                this.messages.add(msg);
-                int bodySize = null == msg.getBody() ? 0 : 
msg.getBody().length;
-                if (bodySize > 0) {
-                    messagesSize.addAndGet(bodySize);
+        long remainingHoldMs() {
+            return createTime + holdMs - System.currentTimeMillis();
+        }
+
+        AddResult add(Message msg, SendCallback sendCallback) {
+            boolean opened;
+            boolean ready;
+            synchronized (this) {
+                if (closed) {
+                    return AddResult.REJECTED;
                 }
+                opened = messages.isEmpty();
+                messages.add(msg);
+                sendCallbacks.add(sendCallback);
+                messagesSize += null == msg.getBody() ? 0 : 
msg.getBody().length;
                 String msgKeys = msg.getKeys();
                 if (msgKeys != null) {
-                    
this.keys.addAll(Arrays.asList(msgKeys.split(MessageConst.KEY_SEPARATOR)));
+                    
keys.addAll(Arrays.asList(msgKeys.split(MessageConst.KEY_SEPARATOR)));
                 }
+                ready = readyToSend();
             }
-            synchronized (this) {
-                while (!this.closed.get()) {
-                    if (readyToSend()) {
-                        this.send();
-                        break;
-                    } else {
-                        this.wait();
-                    }
-                }
-                return ret;
+            if (ready) {
+                send();
             }
+            return opened ? AddResult.OPENED : AddResult.JOINED;
         }
 
-        public boolean add(Message msg,
-            SendCallback sendCallback) throws InterruptedException, 
RemotingException, MQClientException {
-            synchronized (this.closed) {
-                if (this.closed.get()) {
-                    return false;
-                }
-                this.count++;
-                this.messages.add(msg);
-                this.sendCallbacks.add(sendCallback);
-                int bodySize = null == msg.getBody() ? 0 : 
msg.getBody().length;
-                if (bodySize > 0) {
-                    messagesSize.addAndGet(bodySize);
+        /**
+         * Closes the batch and sends it. Only the first caller sends; later 
calls are no-ops.
+         */
+        void send() {
+            synchronized (this) {
+                if (closed) {
+                    return;
                 }
+                closed = true;
+                batches.remove(aggregateKey, this);
             }
-            if (readyToSend()) {
-                this.send(sendCallback);
+            try {
+                if (defaultMQProducer == null) {
+                    throw new IllegalArgumentException("defaultMQProducer is 
null, can not send message");
+                }
+                if (asyncSend) {
+                    defaultMQProducer.sendDirect(batch(), aggregateKey.mq, 
completing(sent));
+                } else {
+                    // the batch carries other callers' messages, so this 
caller's interrupt must not fail it
+                    sent.complete(defaultMQProducer.sendBatchDirect(batch(), 
aggregateKey.mq));
+                }
+            } catch (Throwable e) {
+                sent.completeExceptionally(e);
             }
-            return true;
-
         }
 
-        public synchronized void wakeup() {
-            if (this.closed.get()) {
-                return;
+        private void complete(SendResult sendResult, Throwable error) {
+            currentlyHoldSize.addAndGet(-messagesSize);
+            SendResult[] sendResults = null;
+            if (error == null) {
+                try {
+                    sendResults = splitSendResults(sendResult);
+                } catch (Exception e) {
+                    error = e;
+                }
+            }
+            for (int i = 0; i < sendCallbacks.size(); i++) {
+                try {
+                    if (error == null) {
+                        sendCallbacks.get(i).onSuccess(sendResults[i]);
+                    } else {
+                        sendCallbacks.get(i).onException(error);
+                    }
+                } catch (Throwable e) {
+                    log.warn("execute send callback of batch message failed", 
e);
+                }
             }
-            this.notify();
         }
 
         private MessageBatch batch() {
@@ -429,98 +391,30 @@ public class ProduceAccumulator {
             return messageBatch;
         }
 
-        private void splitSendResults(SendResult sendResult) {
+        private SendResult[] splitSendResults(SendResult sendResult) {
             if (sendResult == null) {
                 throw new IllegalArgumentException("sendResult is null");
             }
+            int count = this.messages.size();
             boolean isBatchConsumerQueue = 
!sendResult.getMsgId().contains(",");
-            this.sendResults = new SendResult[this.count];
+            SendResult[] sendResults = new SendResult[count];
             if (!isBatchConsumerQueue) {
                 String[] msgIds = sendResult.getMsgId().split(",");
                 String[] offsetMsgIds = sendResult.getOffsetMsgId().split(",");
-                if (offsetMsgIds.length != this.count || msgIds.length != 
this.count) {
+                if (offsetMsgIds.length != count || msgIds.length != count) {
                     throw new IllegalArgumentException("sendResult is 
illegal");
                 }
-                for (int i = 0; i < this.count; i++) {
-                    this.sendResults[i] = new 
SendResult(sendResult.getSendStatus(), msgIds[i],
+                for (int i = 0; i < count; i++) {
+                    sendResults[i] = new 
SendResult(sendResult.getSendStatus(), msgIds[i],
                         sendResult.getMessageQueue(), 
sendResult.getQueueOffset() + i,
                         sendResult.getTransactionId(), offsetMsgIds[i], 
sendResult.getRegionId());
                 }
             } else {
-                for (int i = 0; i < this.count; i++) {
-                    this.sendResults[i] = sendResult;
-                }
-            }
-        }
-
-        private void send() throws InterruptedException, MQClientException, 
MQBrokerException, RemotingException {
-            synchronized (this.closed) {
-                if (this.closed.getAndSet(true)) {
-                    return;
-                }
-            }
-            MessageBatch messageBatch = this.batch();
-            SendResult sendResult = null;
-            try {
-                if (defaultMQProducer != null) {
-                    sendResult = defaultMQProducer.sendDirect(messageBatch, 
aggregateKey.mq, null);
-                    this.splitSendResults(sendResult);
-                } else {
-                    throw new IllegalArgumentException("defaultMQProducer is 
null, can not send message");
-                }
-            } finally {
-                currentlyHoldSize.addAndGet(-messagesSize.get());
-                this.notifyAll();
-            }
-        }
-
-        private void send(SendCallback sendCallback) {
-            synchronized (this.closed) {
-                if (this.closed.getAndSet(true)) {
-                    return;
-                }
-            }
-            MessageBatch messageBatch = this.batch();
-            SendResult sendResult = null;
-            try {
-                if (defaultMQProducer != null) {
-                    final int size = messagesSize.get();
-                    defaultMQProducer.sendDirect(messageBatch, 
aggregateKey.mq, new SendCallback() {
-                        @Override
-                        public void onSuccess(SendResult sendResult) {
-                            try {
-                                splitSendResults(sendResult);
-                                int i = 0;
-                                Iterator<SendCallback> it = 
sendCallbacks.iterator();
-                                while (it.hasNext()) {
-                                    SendCallback v = it.next();
-                                    v.onSuccess(sendResults[i++]);
-                                }
-                                if (i != count) {
-                                    throw new 
IllegalArgumentException("sendResult is illegal");
-                                }
-                                currentlyHoldSize.addAndGet(-size);
-                            } catch (Exception e) {
-                                onException(e);
-                            }
-                        }
-
-                        @Override
-                        public void onException(Throwable e) {
-                            for (SendCallback v : sendCallbacks) {
-                                v.onException(e);
-                            }
-                            currentlyHoldSize.addAndGet(-size);
-                        }
-                    });
-                } else {
-                    throw new IllegalArgumentException("defaultMQProducer is 
null, can not send message");
-                }
-            } catch (Exception e) {
-                for (SendCallback v : sendCallbacks) {
-                    v.onException(e);
+                for (int i = 0; i < count; i++) {
+                    sendResults[i] = sendResult;
                 }
             }
+            return sendResults;
         }
     }
 }
diff --git 
a/client/src/test/java/org/apache/rocketmq/client/producer/DefaultMQProducerTest.java
 
b/client/src/test/java/org/apache/rocketmq/client/producer/DefaultMQProducerTest.java
index 33cf0df390..b0c7c4bd3a 100644
--- 
a/client/src/test/java/org/apache/rocketmq/client/producer/DefaultMQProducerTest.java
+++ 
b/client/src/test/java/org/apache/rocketmq/client/producer/DefaultMQProducerTest.java
@@ -540,6 +540,40 @@ public class DefaultMQProducerTest {
         producer.setAutoBatch(false);
     }
 
+    @Test
+    public void testAutoBatch_unbatchableMessageReleasesHoldSize() throws 
Exception {
+        producer.setAutoBatch(true);
+        when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), 
anyLong())).thenReturn(createTopicRoute());
+        long before = accumulator().getCurrentlyHoldSize();
+
+        Message delayMessage = new Message(topic, "delay message 
body".getBytes());
+        delayMessage.setDelayTimeLevel(1);
+        SendResult sendResult = producer.send(delayMessage);
+
+        assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
+        assertThat(accumulator().getCurrentlyHoldSize()).isEqualTo(before);
+        producer.setAutoBatch(false);
+    }
+
+    @Test
+    public void testAutoBatch_invalidMessageReleasesHoldSize() throws 
Exception {
+        producer.setAutoBatch(true);
+        producer.setMaxMessageSize(4);
+        long before = accumulator().getCurrentlyHoldSize();
+        try {
+            producer.send(bigMessage);
+            failBecauseExceptionWasNotThrown(MQClientException.class);
+        } catch (MQClientException e) {
+            assertThat(e).hasMessageContaining("the message body size over max 
value");
+        }
+        assertThat(accumulator().getCurrentlyHoldSize()).isEqualTo(before);
+        producer.setAutoBatch(false);
+    }
+
+    private ProduceAccumulator accumulator() throws NoSuchFieldException, 
IllegalAccessException {
+        return getField(producer, "produceAccumulator", 
ProduceAccumulator.class);
+    }
+
     @Test
     public void testBatchSendMessageSync_Success() throws RemotingException, 
InterruptedException, MQBrokerException, MQClientException {
         producer.setAutoBatch(true);
diff --git 
a/client/src/test/java/org/apache/rocketmq/client/producer/ProduceAccumulatorTest.java
 
b/client/src/test/java/org/apache/rocketmq/client/producer/ProduceAccumulatorTest.java
index 8e76238d47..24075fe7ac 100644
--- 
a/client/src/test/java/org/apache/rocketmq/client/producer/ProduceAccumulatorTest.java
+++ 
b/client/src/test/java/org/apache/rocketmq/client/producer/ProduceAccumulatorTest.java
@@ -20,158 +20,463 @@ package org.apache.rocketmq.client.producer;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 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 java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 import org.apache.rocketmq.client.exception.MQBrokerException;
 import org.apache.rocketmq.client.exception.MQClientException;
 import org.apache.rocketmq.common.message.Message;
 import org.apache.rocketmq.common.message.MessageBatch;
 import org.apache.rocketmq.common.message.MessageQueue;
-import org.apache.rocketmq.remoting.exception.RemotingException;
+import org.junit.After;
 import org.junit.Test;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
 public class ProduceAccumulatorTest {
-    private boolean compareMessageBatch(MessageBatch a, MessageBatch b) {
-        if (!a.getTopic().equals(b.getTopic())) {
-            return false;
+    private static final String TOPIC = "testTopic";
+
+    private final ProduceAccumulator accumulator = new 
ProduceAccumulator("test");
+    private final ExecutorService executor = Executors.newCachedThreadPool();
+
+    @After
+    public void tearDown() {
+        executor.shutdownNow();
+        accumulator.shutdown();
+    }
+
+    /**
+     * Records every batch it receives and answers with {@link #reply}, 
synchronously or through the callback.
+     */
+    private static class FakeProducer extends DefaultMQProducer {
+        interface Reply {
+            SendResult apply(Message msg, MessageQueue mq) throws Exception;
         }
-        if (!Arrays.equals(a.getBody(), b.getBody())) {
-            return false;
+
+        private final Reply reply;
+        private final AtomicInteger sendTimes = new AtomicInteger();
+        private volatile Message lastBatch;
+        private volatile MessageQueue lastQueue;
+
+        FakeProducer() {
+            this((msg, mq) -> ok());
         }
-        return true;
-    }
 
-    private class MockMQProducer extends DefaultMQProducer {
-        private Message beSendMessage = null;
-        private MessageQueue beSendMessageQueue = null;
+        FakeProducer(Reply reply) {
+            this.reply = reply;
+        }
 
         @Override
         public SendResult sendDirect(Message msg, MessageQueue mq,
-            SendCallback sendCallback) {
-            this.beSendMessage = msg;
-            this.beSendMessageQueue = mq;
+            SendCallback sendCallback) throws MQClientException, 
MQBrokerException, InterruptedException {
+            sendTimes.incrementAndGet();
+            lastBatch = msg;
+            lastQueue = mq;
+            SendResult result;
+            try {
+                result = reply.apply(msg, mq);
+            } catch (MQClientException | MQBrokerException | 
InterruptedException | RuntimeException e) {
+                throw e;
+            } catch (Exception e) {
+                throw new IllegalStateException(e);
+            }
+            if (sendCallback != null) {
+                sendCallback.onSuccess(result);
+            }
+            return result;
+        }
 
+        static SendResult ok() {
             SendResult sendResult = new SendResult();
             sendResult.setMsgId("123");
-            if (sendCallback != null) {
-                sendCallback.onSuccess(sendResult);
-            }
             return sendResult;
         }
     }
 
+    private static class RecordingCallback implements SendCallback {
+        private final CountDownLatch done = new CountDownLatch(1);
+        private final AtomicInteger successes = new AtomicInteger();
+        private final AtomicReference<Throwable> error = new 
AtomicReference<>();
+
+        @Override
+        public void onSuccess(SendResult sendResult) {
+            successes.incrementAndGet();
+            done.countDown();
+        }
+
+        @Override
+        public void onException(Throwable e) {
+            error.set(e);
+            done.countDown();
+        }
+
+        boolean await() throws InterruptedException {
+            return done.await(3, TimeUnit.SECONDS);
+        }
+    }
+
+    private static List<Message> messages(String... bodies) {
+        List<Message> messages = new ArrayList<>();
+        for (String body : bodies) {
+            messages.add(new Message(TOPIC, body.getBytes()));
+        }
+        return messages;
+    }
+
+    /**
+     * Reserves hold size first, like {@link 
DefaultMQProducer#sendByAccumulator} does.
+     */
+    private Message reserved(String body) {
+        Message message = new Message(TOPIC, body.getBytes());
+        assertThat(accumulator.tryAddMessage(message)).isTrue();
+        return message;
+    }
+
+    private static MessageQueue queue(int id) {
+        return new MessageQueue(TOPIC, "broker", id);
+    }
+
     @Test
-    public void testProduceAccumulator_async() throws MQBrokerException, 
RemotingException, InterruptedException, MQClientException {
-        MockMQProducer mockMQProducer = new MockMQProducer();
-
-        ProduceAccumulator produceAccumulator = new ProduceAccumulator("test");
-        produceAccumulator.start();
-
-        final CountDownLatch countDownLatch = new CountDownLatch(1);
-        List<Message> messages = new ArrayList<Message>();
-        messages.add(new Message("testTopic", "1".getBytes()));
-        messages.add(new Message("testTopic", "22".getBytes()));
-        messages.add(new Message("testTopic", "333".getBytes()));
-        messages.add(new Message("testTopic", "4444".getBytes()));
-        messages.add(new Message("testTopic", "55555".getBytes()));
+    public void testAsyncSend_batchesMessages() throws Exception {
+        FakeProducer producer = new FakeProducer();
+        accumulator.start();
+        List<Message> messages = messages("1", "22", "333", "4444", "55555");
+        List<RecordingCallback> callbacks = new ArrayList<>();
         for (Message message : messages) {
-            produceAccumulator.send(message, new SendCallback() {
-                final CountDownLatch finalCountDownLatch = countDownLatch;
+            RecordingCallback callback = new RecordingCallback();
+            callbacks.add(callback);
+            accumulator.send(message, null, callback, producer);
+        }
+        for (RecordingCallback callback : callbacks) {
+            assertThat(callback.await()).isTrue();
+        }
 
-                @Override
-                public void onSuccess(SendResult sendResult) {
-                    finalCountDownLatch.countDown();
-                }
+        MessageBatch expected = MessageBatch.generateFromList(messages);
+        expected.setBody(expected.encode());
+        assertThat(producer.sendTimes.get()).isEqualTo(1);
+        
assertThat(producer.lastBatch.getTopic()).isEqualTo(expected.getTopic());
+        assertThat(Arrays.equals(producer.lastBatch.getBody(), 
expected.getBody())).isTrue();
+    }
+
+    @Test
+    public void testSyncSend_batchesConcurrentMessages() throws Exception {
+        FakeProducer producer = new FakeProducer();
+        accumulator.batchMaxDelayMs(3000);
+        List<Message> messages = messages("1", "22", "333", "4444", "55555");
+        List<Future<SendResult>> results = new ArrayList<>();
+        for (Message message : messages) {
+            results.add(executor.submit(() -> accumulator.send(message, null, 
producer)));
+        }
+        for (Future<SendResult> result : results) {
+            assertThat(result.get(5, TimeUnit.SECONDS)).isNotNull();
+        }
+
+        MessageBatch expected = MessageBatch.generateFromList(messages);
+        expected.setBody(expected.encode());
+        assertThat(producer.sendTimes.get()).isEqualTo(1);
+        
assertThat(producer.lastBatch.getTopic()).isEqualTo(expected.getTopic());
+        // The execution order is uncertain, just compare the length
+        
assertThat(producer.lastBatch.getBody().length).isEqualTo(expected.getBody().length);
+    }
+
+    @Test
+    public void testSendWithMessageQueue() throws Exception {
+        FakeProducer producer = new FakeProducer();
+        accumulator.start();
+        MessageQueue messageQueue = new MessageQueue("topicTest", 
"brokerTest", 0);
+
+        accumulator.send(new Message(TOPIC, "1".getBytes()), messageQueue, 
producer);
+        assertThat(producer.lastQueue).isEqualTo(messageQueue);
 
-                @Override
-                public void onException(Throwable e) {
-                    finalCountDownLatch.countDown();
+        producer.lastQueue = null;
+        RecordingCallback callback = new RecordingCallback();
+        accumulator.send(new Message(TOPIC, "1".getBytes()), messageQueue, 
callback, producer);
+        assertThat(callback.await()).isTrue();
+        assertThat(producer.lastQueue).isEqualTo(messageQueue);
+    }
+
+    @Test
+    public void testSyncSend_slowBatchDoesNotBlockOtherBatches() throws 
Exception {
+        CountDownLatch slowSendStarted = new CountDownLatch(1);
+        CountDownLatch releaseSlowSend = new CountDownLatch(1);
+        FakeProducer producer = new FakeProducer((msg, mq) -> {
+            if (queue(0).equals(mq)) {
+                slowSendStarted.countDown();
+                releaseSlowSend.await(10, TimeUnit.SECONDS);
+            }
+            return FakeProducer.ok();
+        });
+        try {
+            Future<SendResult> slow = executor.submit(() -> 
accumulator.send(new Message(TOPIC, "slow".getBytes()), queue(0), producer));
+            assertThat(slowSendStarted.await(3, TimeUnit.SECONDS)).isTrue();
+
+            Future<SendResult> fast = executor.submit(() -> 
accumulator.send(new Message(TOPIC, "fast".getBytes()), queue(1), producer));
+            assertThat(fast.get(2, TimeUnit.SECONDS)).isNotNull();
+
+            releaseSlowSend.countDown();
+            assertThat(slow.get(3, TimeUnit.SECONDS)).isNotNull();
+        } finally {
+            releaseSlowSend.countDown();
+        }
+    }
+
+    @Test
+    public void testSyncSend_failurePropagatesToEveryMessageInBatch() throws 
Exception {
+        FakeProducer producer = new FakeProducer((msg, mq) -> {
+            throw new MQBrokerException(1, "mock broker failure");
+        });
+        accumulator.batchMaxDelayMs(1000);
+        List<Future<Throwable>> outcomes = new ArrayList<>();
+        for (String body : new String[] {"a", "b", "c", "d", "e"}) {
+            Message message = reserved(body);
+            outcomes.add(executor.submit(() -> {
+                try {
+                    accumulator.send(message, null, producer);
+                    return null;
+                } catch (Throwable t) {
+                    return t;
                 }
-            }, mockMQProducer);
+            }));
         }
-        assertThat(countDownLatch.await(3000L, 
TimeUnit.MILLISECONDS)).isTrue();
-        assertThat(mockMQProducer.beSendMessage instanceof 
MessageBatch).isTrue();
+        for (Future<Throwable> outcome : outcomes) {
+            assertThat(outcome.get(5, 
TimeUnit.SECONDS)).isInstanceOf(MQBrokerException.class);
+        }
+        assertThat(producer.sendTimes.get()).isEqualTo(1);
+        assertThat(accumulator.getCurrentlyHoldSize()).isZero();
+    }
 
-        MessageBatch messageBatch1 = (MessageBatch) 
mockMQProducer.beSendMessage;
-        MessageBatch messageBatch2 = MessageBatch.generateFromList(messages);
-        messageBatch2.setBody(messageBatch2.encode());
+    @Test
+    public void testSyncSend_interruptWhileWaitingDoesNotStrandMessage() 
throws Exception {
+        FakeProducer producer = new FakeProducer();
+        accumulator.batchMaxDelayMs(500);
+        AtomicReference<Object> outcome = new AtomicReference<>();
+        AtomicReference<Boolean> interruptedAfterReturn = new 
AtomicReference<>();
+        Thread sender = new Thread(() -> {
+            try {
+                outcome.set(accumulator.send(new Message(TOPIC, 
"1".getBytes()), null, producer));
+            } catch (Throwable t) {
+                outcome.set(t);
+            }
+            interruptedAfterReturn.set(Thread.currentThread().isInterrupted());
+        });
+        sender.start();
+        Thread.sleep(100);
+        sender.interrupt();
+        sender.join(3000);
 
-        assertThat(compareMessageBatch(messageBatch1, messageBatch2)).isTrue();
+        assertThat(sender.isAlive()).isFalse();
+        assertThat(producer.sendTimes.get()).isEqualTo(1);
+        assertThat(outcome.get()).isInstanceOf(SendResult.class);
+        assertThat(interruptedAfterReturn.get()).isTrue();
     }
 
     @Test
-    public void testProduceAccumulator_sync() throws MQBrokerException, 
RemotingException, InterruptedException, MQClientException {
-        final MockMQProducer mockMQProducer = new MockMQProducer();
-
-        final ProduceAccumulator produceAccumulator = new 
ProduceAccumulator("test");
-        produceAccumulator.batchMaxDelayMs(3000);
-        produceAccumulator.start();
-
-        List<Message> messages = new ArrayList<Message>();
-        messages.add(new Message("testTopic", "1".getBytes()));
-        messages.add(new Message("testTopic", "22".getBytes()));
-        messages.add(new Message("testTopic", "333".getBytes()));
-        messages.add(new Message("testTopic", "4444".getBytes()));
-        messages.add(new Message("testTopic", "55555".getBytes()));
-        final CountDownLatch countDownLatch = new 
CountDownLatch(messages.size());
-
-        for (final Message message : messages) {
-            new Thread(new Runnable() {
-                final ProduceAccumulator finalProduceAccumulator = 
produceAccumulator;
-                final CountDownLatch finalCountDownLatch = countDownLatch;
-                final MockMQProducer finalMockMQProducer = mockMQProducer;
-                final Message finalMessage = message;
-
-                @Override
-                public void run() {
-                    try {
-                        finalProduceAccumulator.send(finalMessage, 
finalMockMQProducer);
-                        finalCountDownLatch.countDown();
-                    } catch (Exception e) {
-                        e.printStackTrace();
+    public void testSyncSend_concurrentNoLossNoDuplicate() throws Exception {
+        int threads = 32;
+        int messagesPerThread = 300;
+        Set<String> sentBodies = ConcurrentHashMap.newKeySet();
+        AtomicInteger sentCount = new AtomicInteger();
+        FakeProducer producer = new FakeProducer((msg, mq) -> {
+            for (Message m : (MessageBatch) msg) {
+                sentBodies.add(new String(m.getBody()));
+                sentCount.incrementAndGet();
+            }
+            return FakeProducer.ok();
+        });
+        accumulator.batchMaxDelayMs(1);
+        accumulator.batchMaxBytes(64);
+        List<Future<Integer>> futures = new ArrayList<>();
+        for (int t = 0; t < threads; t++) {
+            int threadId = t;
+            futures.add(executor.submit(() -> {
+                int succeeded = 0;
+                for (int i = 0; i < messagesPerThread; i++) {
+                    Message message = new Message(TOPIC, (threadId + "-" + 
i).getBytes());
+                    if (accumulator.send(message, queue(i % 3), producer) != 
null) {
+                        succeeded++;
                     }
                 }
-            }).start();
+                return succeeded;
+            }));
         }
-        assertThat(countDownLatch.await(5000L, 
TimeUnit.MILLISECONDS)).isTrue();
-        assertThat(mockMQProducer.beSendMessage instanceof 
MessageBatch).isTrue();
-
-        MessageBatch messageBatch1 = (MessageBatch) 
mockMQProducer.beSendMessage;
-        MessageBatch messageBatch2 = MessageBatch.generateFromList(messages);
-        messageBatch2.setBody(messageBatch2.encode());
+        int succeeded = 0;
+        for (Future<Integer> future : futures) {
+            succeeded += future.get(60, TimeUnit.SECONDS);
+        }
+        assertThat(succeeded).isEqualTo(threads * messagesPerThread);
+        assertThat(sentCount.get()).isEqualTo(threads * messagesPerThread);
+        assertThat(sentBodies).hasSize(threads * messagesPerThread);
+    }
 
-        
assertThat(messageBatch1.getTopic()).isEqualTo(messageBatch2.getTopic());
-        // The execution order is uncertain, just compare the length
-        
assertThat(messageBatch1.getBody().length).isEqualTo(messageBatch2.getBody().length);
+    @Test
+    public void testTryAddMessage_concurrentAccountingIsExact() throws 
Exception {
+        int totalHoldSize = 1000;
+        accumulator.totalBatchMaxBytes(totalHoldSize);
+        CountDownLatch start = new CountDownLatch(1);
+        AtomicInteger accepted = new AtomicInteger();
+        List<Future<?>> futures = new ArrayList<>();
+        for (int t = 0; t < 16; t++) {
+            futures.add(executor.submit(() -> {
+                start.await();
+                for (int i = 0; i < 500; i++) {
+                    if (accumulator.tryAddMessage(new Message(TOPIC, new 
byte[] {1}))) {
+                        accepted.incrementAndGet();
+                    }
+                }
+                return null;
+            }));
+        }
+        start.countDown();
+        for (Future<?> future : futures) {
+            future.get(10, TimeUnit.SECONDS);
+        }
+        assertThat(accepted.get()).isEqualTo(totalHoldSize);
     }
 
     @Test
-    public void testProduceAccumulator_sendWithMessageQueue() throws 
MQBrokerException, RemotingException, InterruptedException, MQClientException {
-        MockMQProducer mockMQProducer = new MockMQProducer();
+    public void testAsyncSend_synchronousSendFailureReleasesHoldSize() throws 
Exception {
+        FakeProducer producer = new FakeProducer((msg, mq) -> {
+            throw new MQClientException("executor rejected", null);
+        });
+        accumulator.batchMaxBytes(1);
+        RecordingCallback callback = new RecordingCallback();
+        accumulator.send(reserved("22"), null, callback, producer);
 
-        MessageQueue messageQueue = new MessageQueue("topicTest", 
"brokerTest", 0);
-        final ProduceAccumulator produceAccumulator = new 
ProduceAccumulator("test");
-        produceAccumulator.start();
+        assertThat(callback.await()).isTrue();
+        assertThat(callback.error.get()).isInstanceOf(MQClientException.class);
+        assertThat(accumulator.getCurrentlyHoldSize()).isZero();
+    }
 
-        Message message = new Message("testTopic", "1".getBytes());
-        produceAccumulator.send(message, messageQueue, mockMQProducer);
-        assertThat(mockMQProducer.beSendMessageQueue).isEqualTo(messageQueue);
+    @Test
+    public void testSentBatchesAreRemoved() throws Exception {
+        FakeProducer producer = new FakeProducer();
+        accumulator.start();
+        List<RecordingCallback> callbacks = new ArrayList<>();
+        for (int i = 0; i < 10; i++) {
+            accumulator.send(new Message(TOPIC, "s".getBytes()), queue(i), 
producer);
+            RecordingCallback callback = new RecordingCallback();
+            callbacks.add(callback);
+            accumulator.send(new Message(TOPIC, "a".getBytes()), queue(i), 
callback, producer);
+        }
+        for (RecordingCallback callback : callbacks) {
+            assertThat(callback.await()).isTrue();
+        }
+        assertThat(accumulator.pendingBatchCount()).isZero();
+    }
 
-        final CountDownLatch countDownLatch = new CountDownLatch(1);
-        produceAccumulator.send(message, messageQueue, new SendCallback() {
+    @Test
+    public void testAsyncSend_throwingCallbackDoesNotAffectOthers() {
+        FakeProducer producer = new FakeProducer();
+        accumulator.batchMaxDelayMs(30 * 1000);
+        accumulator.batchMaxBytes(1);
+        RecordingCallback throwing = new RecordingCallback() {
             @Override
             public void onSuccess(SendResult sendResult) {
-                countDownLatch.countDown();
+                super.onSuccess(sendResult);
+                throw new IllegalStateException("user callback bug");
             }
+        };
+        RecordingCallback other = new RecordingCallback();
 
-            @Override
-            public void onException(Throwable e) {
-                countDownLatch.countDown();
+        accumulator.send(reserved("1"), null, throwing, producer);
+        accumulator.send(reserved("2"), null, other, producer);
+
+        assertThat(throwing.successes.get() + 
other.successes.get()).isEqualTo(2);
+        assertThat(throwing.error.get()).isNull();
+        assertThat(other.error.get()).isNull();
+        assertThat(accumulator.getCurrentlyHoldSize()).isZero();
+    }
+
+    @Test
+    public void testSyncSend_firstCallerSendsBatchOnHoldTimeout() throws 
Exception {
+        AtomicReference<Thread> sender = new AtomicReference<>();
+        FakeProducer producer = new FakeProducer((msg, mq) -> {
+            sender.set(Thread.currentThread());
+            return FakeProducer.ok();
+        });
+        accumulator.batchMaxDelayMs(300);
+        List<Thread> callers = new ArrayList<>();
+        for (int i = 0; i < 4; i++) {
+            Message message = new Message(TOPIC, ("caller-" + i).getBytes());
+            Thread caller = new Thread(() -> {
+                try {
+                    accumulator.send(message, null, producer);
+                } catch (Exception e) {
+                    throw new IllegalStateException(e);
+                }
+            });
+            callers.add(caller);
+            caller.start();
+            if (i == 0) {
+                // let the first caller open the batch before the others join 
it
+                Thread.sleep(50);
             }
-        }, mockMQProducer);
-        assertThat(countDownLatch.await(3000L, 
TimeUnit.MILLISECONDS)).isTrue();
-        assertThat(mockMQProducer.beSendMessageQueue).isEqualTo(messageQueue);
+        }
+        for (Thread caller : callers) {
+            caller.join(3000);
+            assertThat(caller.isAlive()).isFalse();
+        }
+        assertThat(producer.sendTimes.get()).isEqualTo(1);
+        assertThat(sender.get()).isSameAs(callers.get(0));
+    }
+
+    @Test
+    public void testSyncSend_batchSendIsNotAbortedByCallerInterrupt() throws 
Exception {
+        CountDownLatch sendStarted = new CountDownLatch(1);
+        AtomicInteger attempts = new AtomicInteger();
+        FakeProducer producer = new FakeProducer((msg, mq) -> {
+            if (attempts.incrementAndGet() == 1) {
+                // interrupted while the shared batch is in flight
+                sendStarted.countDown();
+                Thread.sleep(5000);
+            }
+            return FakeProducer.ok();
+        });
+        accumulator.batchMaxDelayMs(200);
+        AtomicReference<Object> triggerOutcome = new AtomicReference<>();
+        AtomicReference<Object> otherOutcome = new AtomicReference<>();
+        AtomicReference<Boolean> triggerInterrupted = new AtomicReference<>();
+        AtomicReference<Thread> trigger = new AtomicReference<>();
+        Message triggerMessage = reserved("trigger");
+        Message joinerMessage = reserved("joiner");
+
+        Thread joiner = new Thread(() -> {
+            try {
+                otherOutcome.set(accumulator.send(joinerMessage, null, 
producer));
+            } catch (Throwable t) {
+                otherOutcome.set(t);
+            }
+        });
+        Thread caller = new Thread(() -> {
+            try {
+                triggerOutcome.set(accumulator.send(triggerMessage, null, 
producer));
+            } catch (Throwable t) {
+                triggerOutcome.set(t);
+            }
+            triggerInterrupted.set(Thread.currentThread().isInterrupted());
+        });
+        trigger.set(caller);
+        caller.start();
+        Thread.sleep(20);
+        joiner.start();
+        assertThat(sendStarted.await(3, TimeUnit.SECONDS)).isTrue();
+
+        caller.interrupt();
+        caller.join(5000);
+        joiner.join(5000);
+
+        assertThat(caller.isAlive()).isFalse();
+        assertThat(joiner.isAlive()).isFalse();
+        // this caller's interrupt must not fail the message that joined the 
same batch
+        assertThat(otherOutcome.get()).isInstanceOf(SendResult.class);
+        assertThat(triggerOutcome.get()).isInstanceOf(SendResult.class);
+        assertThat(triggerInterrupted.get()).isTrue();
+        assertThat(accumulator.getCurrentlyHoldSize()).isZero();
     }
 }

Reply via email to