001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.broker.region;
018
019import java.io.IOException;
020import java.util.ArrayList;
021import java.util.Iterator;
022import java.util.LinkedList;
023import java.util.List;
024import java.util.concurrent.CountDownLatch;
025import java.util.concurrent.TimeUnit;
026import java.util.concurrent.atomic.AtomicInteger;
027
028import javax.jms.JMSException;
029
030import org.apache.activemq.broker.Broker;
031import org.apache.activemq.broker.ConnectionContext;
032import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
033import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor;
034import org.apache.activemq.command.ConsumerControl;
035import org.apache.activemq.command.ConsumerInfo;
036import org.apache.activemq.command.Message;
037import org.apache.activemq.command.MessageAck;
038import org.apache.activemq.command.MessageDispatch;
039import org.apache.activemq.command.MessageDispatchNotification;
040import org.apache.activemq.command.MessageId;
041import org.apache.activemq.command.MessagePull;
042import org.apache.activemq.command.Response;
043import org.apache.activemq.thread.Scheduler;
044import org.apache.activemq.transaction.Synchronization;
045import org.apache.activemq.transport.TransmitCallback;
046import org.apache.activemq.usage.SystemUsage;
047import org.slf4j.Logger;
048import org.slf4j.LoggerFactory;
049
050/**
051 * A subscription that honors the pre-fetch option of the ConsumerInfo.
052 */
053public abstract class PrefetchSubscription extends AbstractSubscription {
054
055    private static final Logger LOG = LoggerFactory.getLogger(PrefetchSubscription.class);
056    protected final Scheduler scheduler;
057
058    protected PendingMessageCursor pending;
059    protected final List<MessageReference> dispatched = new ArrayList<MessageReference>();
060    protected final AtomicInteger prefetchExtension = new AtomicInteger();
061    protected boolean usePrefetchExtension = true;
062    private int maxProducersToAudit=32;
063    private int maxAuditDepth=2048;
064    protected final SystemUsage usageManager;
065    protected final Object pendingLock = new Object();
066    protected final Object dispatchLock = new Object();
067    private final CountDownLatch okForAckAsDispatchDone = new CountDownLatch(1);
068
069    public PrefetchSubscription(Broker broker, SystemUsage usageManager, ConnectionContext context, ConsumerInfo info, PendingMessageCursor cursor) throws JMSException {
070        super(broker,context, info);
071        this.usageManager=usageManager;
072        pending = cursor;
073        try {
074            pending.start();
075        } catch (Exception e) {
076            throw new JMSException(e.getMessage());
077        }
078        this.scheduler = broker.getScheduler();
079    }
080
081    public PrefetchSubscription(Broker broker,SystemUsage usageManager, ConnectionContext context, ConsumerInfo info) throws JMSException {
082        this(broker,usageManager,context, info, new VMPendingMessageCursor(false));
083    }
084
085    /**
086     * Allows a message to be pulled on demand by a client
087     */
088    @Override
089    public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception {
090        // The slave should not deliver pull messages.
091        // TODO: when the slave becomes a master, He should send a NULL message to all the
092        // consumers to 'wake them up' in case they were waiting for a message.
093        if (getPrefetchSize() == 0) {
094            prefetchExtension.set(pull.getQuantity());
095            final long dispatchCounterBeforePull = getSubscriptionStatistics().getDispatched().getCount();
096
097            // Have the destination push us some messages.
098            for (Destination dest : destinations) {
099                dest.iterate();
100            }
101            dispatchPending();
102
103            synchronized(this) {
104                // If there was nothing dispatched.. we may need to setup a timeout.
105                if (dispatchCounterBeforePull == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) {
106                    // immediate timeout used by receiveNoWait()
107                    if (pull.getTimeout() == -1) {
108                        // Null message indicates the pull is done or did not have pending.
109                        prefetchExtension.set(1);
110                        add(QueueMessageReference.NULL_MESSAGE);
111                        dispatchPending();
112                    }
113                    if (pull.getTimeout() > 0) {
114                        scheduler.executeAfterDelay(new Runnable() {
115                            @Override
116                            public void run() {
117                                pullTimeout(dispatchCounterBeforePull, pull.isAlwaysSignalDone());
118                            }
119                        }, pull.getTimeout());
120                    }
121                }
122            }
123        }
124        return null;
125    }
126
127    /**
128     * Occurs when a pull times out. If nothing has been dispatched since the
129     * timeout was setup, then send the NULL message.
130     */
131    final void pullTimeout(long dispatchCounterBeforePull, boolean alwaysSignalDone) {
132        synchronized (pendingLock) {
133            if (dispatchCounterBeforePull == getSubscriptionStatistics().getDispatched().getCount() || alwaysSignalDone) {
134                try {
135                    prefetchExtension.set(1);
136                    add(QueueMessageReference.NULL_MESSAGE);
137                    dispatchPending();
138                } catch (Exception e) {
139                    context.getConnection().serviceException(e);
140                } finally {
141                    prefetchExtension.set(0);
142                }
143            }
144        }
145    }
146
147    @Override
148    public void add(MessageReference node) throws Exception {
149        synchronized (pendingLock) {
150            // The destination may have just been removed...
151            if (!destinations.contains(node.getRegionDestination()) && node != QueueMessageReference.NULL_MESSAGE) {
152                // perhaps we should inform the caller that we are no longer valid to dispatch to?
153                return;
154            }
155
156            // Don't increment for the pullTimeout control message.
157            if (!node.equals(QueueMessageReference.NULL_MESSAGE)) {
158                getSubscriptionStatistics().getEnqueues().increment();
159            }
160            pending.addMessageLast(node);
161        }
162        dispatchPending();
163    }
164
165    @Override
166    public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception {
167        synchronized(pendingLock) {
168            try {
169                pending.reset();
170                while (pending.hasNext()) {
171                    MessageReference node = pending.next();
172                    node.decrementReferenceCount();
173                    if (node.getMessageId().equals(mdn.getMessageId())) {
174                        // Synchronize between dispatched list and removal of messages from pending list
175                        // related to remove subscription action
176                        synchronized(dispatchLock) {
177                            pending.remove();
178                            createMessageDispatch(node, node.getMessage());
179                            dispatched.add(node);
180                            getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize());
181                            onDispatch(node, node.getMessage());
182                        }
183                        return;
184                    }
185                }
186            } finally {
187                pending.release();
188            }
189        }
190        throw new JMSException(
191                "Slave broker out of sync with master: Dispatched message ("
192                        + mdn.getMessageId() + ") was not in the pending list for "
193                        + mdn.getConsumerId() + " on " + mdn.getDestination().getPhysicalName());
194    }
195
196    @Override
197    public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception {
198        // Handle the standard acknowledgment case.
199        boolean callDispatchMatched = false;
200        Destination destination = null;
201
202        if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) {
203            // suppress unexpected ack exception in this expected case
204            LOG.warn("Ignoring ack received before dispatch; result of failover with an outstanding ack. Acked messages will be replayed if present on this broker. Ignored ack: {}", ack);
205            return;
206        }
207
208        LOG.trace("ack: {}", ack);
209
210        synchronized(dispatchLock) {
211            if (ack.isStandardAck()) {
212                // First check if the ack matches the dispatched. When using failover this might
213                // not be the case. We don't ever want to ack the wrong messages.
214                assertAckMatchesDispatched(ack);
215
216                // Acknowledge all dispatched messages up till the message id of
217                // the acknowledgment.
218                boolean inAckRange = false;
219                List<MessageReference> removeList = new ArrayList<MessageReference>();
220                for (final MessageReference node : dispatched) {
221                    MessageId messageId = node.getMessageId();
222                    if (ack.getFirstMessageId() == null
223                            || ack.getFirstMessageId().equals(messageId)) {
224                        inAckRange = true;
225                    }
226                    if (inAckRange) {
227                        // Don't remove the nodes until we are committed.
228                        if (!context.isInTransaction()) {
229                            getSubscriptionStatistics().getDequeues().increment();
230                            ((Destination)node.getRegionDestination()).getDestinationStatistics().getInflight().decrement();
231                            removeList.add(node);
232                        } else {
233                            registerRemoveSync(context, node);
234                        }
235                        acknowledge(context, ack, node);
236                        if (ack.getLastMessageId().equals(messageId)) {
237                            destination = (Destination) node.getRegionDestination();
238                            callDispatchMatched = true;
239                            break;
240                        }
241                    }
242                }
243                for (final MessageReference node : removeList) {
244                    dispatched.remove(node);
245                    getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
246                }
247                // this only happens after a reconnect - get an ack which is not
248                // valid
249                if (!callDispatchMatched) {
250                    LOG.warn("Could not correlate acknowledgment with dispatched message: {}", ack);
251                }
252            } else if (ack.isIndividualAck()) {
253                // Message was delivered and acknowledge - but only delete the
254                // individual message
255                for (final MessageReference node : dispatched) {
256                    MessageId messageId = node.getMessageId();
257                    if (ack.getLastMessageId().equals(messageId)) {
258                        // Don't remove the nodes until we are committed - immediateAck option
259                        if (!context.isInTransaction()) {
260                            getSubscriptionStatistics().getDequeues().increment();
261                            ((Destination)node.getRegionDestination()).getDestinationStatistics().getInflight().decrement();
262                            dispatched.remove(node);
263                            getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
264                        } else {
265                            registerRemoveSync(context, node);
266                        }
267
268                        if (usePrefetchExtension && getPrefetchSize() != 0 && ack.isInTransaction()) {
269                            // allow transaction batch to exceed prefetch
270                            while (true) {
271                                int currentExtension = prefetchExtension.get();
272                                int newExtension = Math.max(currentExtension, currentExtension + 1);
273                                if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
274                                    break;
275                                }
276                            }
277                        }
278
279                        acknowledge(context, ack, node);
280                        destination = (Destination) node.getRegionDestination();
281                        callDispatchMatched = true;
282                        break;
283                    }
284                }
285            }else if (ack.isDeliveredAck()) {
286                // Message was delivered but not acknowledged: update pre-fetch
287                // counters.
288                int index = 0;
289                for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
290                    final MessageReference node = iter.next();
291                    Destination nodeDest = (Destination) node.getRegionDestination();
292                    if (ack.getLastMessageId().equals(node.getMessageId())) {
293                        if (usePrefetchExtension && getPrefetchSize() != 0) {
294                            // allow  batch to exceed prefetch
295                            while (true) {
296                                int currentExtension = prefetchExtension.get();
297                                int newExtension = Math.max(currentExtension, index + 1);
298                                if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
299                                    break;
300                                }
301                            }
302                        }
303                        destination = nodeDest;
304                        callDispatchMatched = true;
305                        break;
306                    }
307                }
308                if (!callDispatchMatched) {
309                    throw new JMSException(
310                            "Could not correlate acknowledgment with dispatched message: "
311                                    + ack);
312                }
313            } else if (ack.isExpiredAck()) {
314                // Message was expired
315                int index = 0;
316                boolean inAckRange = false;
317                for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
318                    final MessageReference node = iter.next();
319                    Destination nodeDest = (Destination) node.getRegionDestination();
320                    MessageId messageId = node.getMessageId();
321                    if (ack.getFirstMessageId() == null
322                            || ack.getFirstMessageId().equals(messageId)) {
323                        inAckRange = true;
324                    }
325                    if (inAckRange) {
326                        if (node.isExpired()) {
327                            if (broker.isExpired(node)) {
328                                Destination regionDestination = nodeDest;
329                                regionDestination.messageExpired(context, this, node);
330                            }
331                            iter.remove();
332                            nodeDest.getDestinationStatistics().getInflight().decrement();
333                        }
334                        if (ack.getLastMessageId().equals(messageId)) {
335                            if (usePrefetchExtension && getPrefetchSize() != 0) {
336                                // allow  batch to exceed prefetch
337                                while (true) {
338                                    int currentExtension = prefetchExtension.get();
339                                    int newExtension = Math.max(currentExtension, index + 1);
340                                    if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
341                                        break;
342                                    }
343                                }
344                            }
345
346                            destination = (Destination) node.getRegionDestination();
347                            callDispatchMatched = true;
348                            break;
349                        }
350                    }
351                }
352                if (!callDispatchMatched) {
353                    throw new JMSException(
354                            "Could not correlate expiration acknowledgment with dispatched message: "
355                                    + ack);
356                }
357            } else if (ack.isRedeliveredAck()) {
358                // Message was re-delivered but it was not yet considered to be
359                // a DLQ message.
360                boolean inAckRange = false;
361                for (final MessageReference node : dispatched) {
362                    MessageId messageId = node.getMessageId();
363                    if (ack.getFirstMessageId() == null
364                            || ack.getFirstMessageId().equals(messageId)) {
365                        inAckRange = true;
366                    }
367                    if (inAckRange) {
368                        if (ack.getLastMessageId().equals(messageId)) {
369                            destination = (Destination) node.getRegionDestination();
370                            callDispatchMatched = true;
371                            break;
372                        }
373                    }
374                }
375                if (!callDispatchMatched) {
376                    throw new JMSException(
377                            "Could not correlate acknowledgment with dispatched message: "
378                                    + ack);
379                }
380            } else if (ack.isPoisonAck()) {
381                // TODO: what if the message is already in a DLQ???
382                // Handle the poison ACK case: we need to send the message to a
383                // DLQ
384                if (ack.isInTransaction()) {
385                    throw new JMSException("Poison ack cannot be transacted: "
386                            + ack);
387                }
388                int index = 0;
389                boolean inAckRange = false;
390                List<MessageReference> removeList = new ArrayList<MessageReference>();
391                for (final MessageReference node : dispatched) {
392                    MessageId messageId = node.getMessageId();
393                    if (ack.getFirstMessageId() == null
394                            || ack.getFirstMessageId().equals(messageId)) {
395                        inAckRange = true;
396                    }
397                    if (inAckRange) {
398                        sendToDLQ(context, node, ack.getPoisonCause());
399                        Destination nodeDest = (Destination) node.getRegionDestination();
400                        nodeDest.getDestinationStatistics()
401                        .getInflight().decrement();
402                        removeList.add(node);
403                        getSubscriptionStatistics().getDequeues().increment();
404                        index++;
405                        acknowledge(context, ack, node);
406                        if (ack.getLastMessageId().equals(messageId)) {
407                            while (true) {
408                                int currentExtension = prefetchExtension.get();
409                                int newExtension = Math.max(0, currentExtension - (index + 1));
410                                if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
411                                    break;
412                                }
413                            }
414                            destination = nodeDest;
415                            callDispatchMatched = true;
416                            break;
417                        }
418                    }
419                }
420                for (final MessageReference node : removeList) {
421                    dispatched.remove(node);
422                    getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
423                }
424                if (!callDispatchMatched) {
425                    throw new JMSException(
426                            "Could not correlate acknowledgment with dispatched message: "
427                                    + ack);
428                }
429            }
430        }
431        if (callDispatchMatched && destination != null) {
432            destination.wakeup();
433            dispatchPending();
434
435            if (pending.isEmpty()) {
436                for (Destination dest : destinations) {
437                    dest.wakeup();
438                }
439            }
440        } else {
441            LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): {}", ack);
442        }
443    }
444
445    private void registerRemoveSync(ConnectionContext context, final MessageReference node) {
446        // setup a Synchronization to remove nodes from the
447        // dispatched list.
448        context.getTransaction().addSynchronization(
449                new Synchronization() {
450
451                    @Override
452                    public void beforeEnd() {
453                        if (usePrefetchExtension && getPrefetchSize() != 0) {
454                            while (true) {
455                                int currentExtension = prefetchExtension.get();
456                                int newExtension = Math.max(0, currentExtension - 1);
457                                if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
458                                    break;
459                                }
460                            }
461                        }
462                    }
463
464                    @Override
465                    public void afterCommit()
466                            throws Exception {
467                        Destination nodeDest = (Destination) node.getRegionDestination();
468                        synchronized(dispatchLock) {
469                            getSubscriptionStatistics().getDequeues().increment();
470                            dispatched.remove(node);
471                            getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize());
472                            nodeDest.getDestinationStatistics().getInflight().decrement();
473                        }
474                        nodeDest.wakeup();
475                        dispatchPending();
476                    }
477
478                    @Override
479                    public void afterRollback() throws Exception {
480                        synchronized(dispatchLock) {
481                            // poisionAck will decrement - otherwise still inflight on client
482                        }
483                    }
484                });
485    }
486
487    /**
488     * Checks an ack versus the contents of the dispatched list.
489     *  called with dispatchLock held
490     * @param ack
491     * @throws JMSException if it does not match
492     */
493    protected void assertAckMatchesDispatched(MessageAck ack) throws JMSException {
494        MessageId firstAckedMsg = ack.getFirstMessageId();
495        MessageId lastAckedMsg = ack.getLastMessageId();
496        int checkCount = 0;
497        boolean checkFoundStart = false;
498        boolean checkFoundEnd = false;
499        for (MessageReference node : dispatched) {
500
501            if (firstAckedMsg == null) {
502                checkFoundStart = true;
503            } else if (!checkFoundStart && firstAckedMsg.equals(node.getMessageId())) {
504                checkFoundStart = true;
505            }
506
507            if (checkFoundStart) {
508                checkCount++;
509            }
510
511            if (lastAckedMsg != null && lastAckedMsg.equals(node.getMessageId())) {
512                checkFoundEnd = true;
513                break;
514            }
515        }
516        if (!checkFoundStart && firstAckedMsg != null)
517            throw new JMSException("Unmatched acknowledge: " + ack
518                    + "; Could not find Message-ID " + firstAckedMsg
519                    + " in dispatched-list (start of ack)");
520        if (!checkFoundEnd && lastAckedMsg != null)
521            throw new JMSException("Unmatched acknowledge: " + ack
522                    + "; Could not find Message-ID " + lastAckedMsg
523                    + " in dispatched-list (end of ack)");
524        if (ack.getMessageCount() != checkCount && !ack.isInTransaction()) {
525            throw new JMSException("Unmatched acknowledge: " + ack
526                    + "; Expected message count (" + ack.getMessageCount()
527                    + ") differs from count in dispatched-list (" + checkCount
528                    + ")");
529        }
530    }
531
532    /**
533     *
534     * @param context
535     * @param node
536     * @param poisonCause
537     * @throws IOException
538     * @throws Exception
539     */
540    protected void sendToDLQ(final ConnectionContext context, final MessageReference node, Throwable poisonCause) throws IOException, Exception {
541        broker.getRoot().sendToDeadLetterQueue(context, node, this, poisonCause);
542    }
543
544    @Override
545    public int getInFlightSize() {
546        return dispatched.size();
547    }
548
549    /**
550     * Used to determine if the broker can dispatch to the consumer.
551     *
552     * @return true if the subscription is full
553     */
554    @Override
555    public boolean isFull() {
556        return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : dispatched.size() - prefetchExtension.get() >= info.getPrefetchSize();
557    }
558
559    /**
560     * @return true when 60% or more room is left for dispatching messages
561     */
562    @Override
563    public boolean isLowWaterMark() {
564        return (dispatched.size() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4);
565    }
566
567    /**
568     * @return true when 10% or less room is left for dispatching messages
569     */
570    @Override
571    public boolean isHighWaterMark() {
572        return (dispatched.size() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9);
573    }
574
575    @Override
576    public int countBeforeFull() {
577        return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - dispatched.size();
578    }
579
580    @Override
581    public int getPendingQueueSize() {
582        return pending.size();
583    }
584
585    @Override
586    public long getPendingMessageSize() {
587        synchronized (pendingLock) {
588            return pending.messageSize();
589        }
590    }
591
592    @Override
593    public int getDispatchedQueueSize() {
594        return dispatched.size();
595    }
596
597    @Override
598    public long getDequeueCounter() {
599        return getSubscriptionStatistics().getDequeues().getCount();
600    }
601
602    @Override
603    public long getDispatchedCounter() {
604        return getSubscriptionStatistics().getDispatched().getCount();
605    }
606
607    @Override
608    public long getEnqueueCounter() {
609        return getSubscriptionStatistics().getEnqueues().getCount();
610    }
611
612    @Override
613    public boolean isRecoveryRequired() {
614        return pending.isRecoveryRequired();
615    }
616
617    public PendingMessageCursor getPending() {
618        return this.pending;
619    }
620
621    public void setPending(PendingMessageCursor pending) {
622        this.pending = pending;
623        if (this.pending!=null) {
624            this.pending.setSystemUsage(usageManager);
625            this.pending.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark());
626        }
627    }
628
629    @Override
630    public void add(ConnectionContext context, Destination destination) throws Exception {
631        synchronized(pendingLock) {
632            super.add(context, destination);
633            pending.add(context, destination);
634        }
635    }
636
637    @Override
638    public List<MessageReference> remove(ConnectionContext context, Destination destination) throws Exception {
639        return remove(context, destination, dispatched);
640    }
641
642    public List<MessageReference> remove(ConnectionContext context, Destination destination, List<MessageReference> dispatched) throws Exception {
643        LinkedList<MessageReference> redispatch = new LinkedList<MessageReference>();
644        synchronized(pendingLock) {
645            super.remove(context, destination);
646            // Here is a potential problem concerning Inflight stat:
647            // Messages not already committed or rolled back may not be removed from dispatched list at the moment
648            // Except if each commit or rollback callback action comes before remove of subscriber.
649            redispatch.addAll(pending.remove(context, destination));
650
651            if (dispatched == null) {
652                return redispatch;
653            }
654
655            // Synchronized to DispatchLock if necessary
656            if (dispatched == this.dispatched) {
657                synchronized(dispatchLock) {
658                    addReferencesAndUpdateRedispatch(redispatch, destination, dispatched);
659                }
660            } else {
661                addReferencesAndUpdateRedispatch(redispatch, destination, dispatched);
662            }
663        }
664
665        return redispatch;
666    }
667
668    private void addReferencesAndUpdateRedispatch(LinkedList<MessageReference> redispatch, Destination destination, List<MessageReference> dispatched) {
669        ArrayList<MessageReference> references = new ArrayList<MessageReference>();
670        for (MessageReference r : dispatched) {
671            if (r.getRegionDestination() == destination) {
672                references.add(r);
673                getSubscriptionStatistics().getInflightMessageSize().addSize(-r.getSize());
674            }
675        }
676        redispatch.addAll(0, references);
677        destination.getDestinationStatistics().getInflight().subtract(references.size());
678        dispatched.removeAll(references);
679    }
680
681    // made public so it can be used in MQTTProtocolConverter
682    public void dispatchPending() throws IOException {
683        synchronized(pendingLock) {
684            try {
685                int numberToDispatch = countBeforeFull();
686                if (numberToDispatch > 0) {
687                    setSlowConsumer(false);
688                    setPendingBatchSize(pending, numberToDispatch);
689                    int count = 0;
690                    pending.reset();
691                    while (pending.hasNext() && !isFull() && count < numberToDispatch) {
692                        MessageReference node = pending.next();
693                        if (node == null) {
694                            break;
695                        }
696
697                        // Synchronize between dispatched list and remove of message from pending list
698                        // related to remove subscription action
699                        synchronized(dispatchLock) {
700                            pending.remove();
701                            if (!isDropped(node) && canDispatch(node)) {
702
703                                // Message may have been sitting in the pending
704                                // list a while waiting for the consumer to ak the message.
705                                if (node != QueueMessageReference.NULL_MESSAGE && node.isExpired()) {
706                                    //increment number to dispatch
707                                    numberToDispatch++;
708                                    if (broker.isExpired(node)) {
709                                        ((Destination)node.getRegionDestination()).messageExpired(context, this, node);
710                                    }
711
712                                    if (!isBrowser()) {
713                                        node.decrementReferenceCount();
714                                        continue;
715                                    }
716                                }
717                                dispatch(node);
718                                count++;
719                            }
720                        }
721                        // decrement after dispatch has taken ownership to avoid usage jitter
722                        node.decrementReferenceCount();
723                    }
724                } else if (!isSlowConsumer()) {
725                    setSlowConsumer(true);
726                    for (Destination dest :destinations) {
727                        dest.slowConsumer(context, this);
728                    }
729                }
730            } finally {
731                pending.release();
732            }
733        }
734    }
735
736    protected void setPendingBatchSize(PendingMessageCursor pending, int numberToDispatch) {
737        pending.setMaxBatchSize(numberToDispatch);
738    }
739
740    // called with dispatchLock held
741    protected boolean dispatch(final MessageReference node) throws IOException {
742        final Message message = node.getMessage();
743        if (message == null) {
744            return false;
745        }
746
747        okForAckAsDispatchDone.countDown();
748
749        MessageDispatch md = createMessageDispatch(node, message);
750        if (node != QueueMessageReference.NULL_MESSAGE) {
751            getSubscriptionStatistics().getDispatched().increment();
752            dispatched.add(node);
753            getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize());
754        }
755        if (getPrefetchSize() == 0) {
756            while (true) {
757                int currentExtension = prefetchExtension.get();
758                int newExtension = Math.max(0, currentExtension - 1);
759                if (prefetchExtension.compareAndSet(currentExtension, newExtension)) {
760                    break;
761                }
762            }
763        }
764        if (info.isDispatchAsync()) {
765            md.setTransmitCallback(new TransmitCallback() {
766
767                @Override
768                public void onSuccess() {
769                    // Since the message gets queued up in async dispatch, we don't want to
770                    // decrease the reference count until it gets put on the wire.
771                    onDispatch(node, message);
772                }
773
774                @Override
775                public void onFailure() {
776                    Destination nodeDest = (Destination) node.getRegionDestination();
777                    if (nodeDest != null) {
778                        if (node != QueueMessageReference.NULL_MESSAGE) {
779                            nodeDest.getDestinationStatistics().getDispatched().increment();
780                            nodeDest.getDestinationStatistics().getInflight().increment();
781                            LOG.trace("{} failed to dispatch: {} - {}, dispatched: {}, inflight: {}", new Object[]{ info.getConsumerId(), message.getMessageId(), message.getDestination(), getSubscriptionStatistics().getDispatched().getCount(), dispatched.size() });
782                        }
783                    }
784                    if (node instanceof QueueMessageReference) {
785                        ((QueueMessageReference) node).unlock();
786                    }
787                }
788            });
789            context.getConnection().dispatchAsync(md);
790        } else {
791            context.getConnection().dispatchSync(md);
792            onDispatch(node, message);
793        }
794        return true;
795    }
796
797    protected void onDispatch(final MessageReference node, final Message message) {
798        Destination nodeDest = (Destination) node.getRegionDestination();
799        if (nodeDest != null) {
800            if (node != QueueMessageReference.NULL_MESSAGE) {
801                nodeDest.getDestinationStatistics().getDispatched().increment();
802                nodeDest.getDestinationStatistics().getInflight().increment();
803                LOG.trace("{} dispatched: {} - {}, dispatched: {}, inflight: {}", new Object[]{ info.getConsumerId(), message.getMessageId(), message.getDestination(), getSubscriptionStatistics().getDispatched().getCount(), dispatched.size() });
804            }
805        }
806
807        if (info.isDispatchAsync()) {
808            try {
809                dispatchPending();
810            } catch (IOException e) {
811                context.getConnection().serviceExceptionAsync(e);
812            }
813        }
814    }
815
816    /**
817     * inform the MessageConsumer on the client to change it's prefetch
818     *
819     * @param newPrefetch
820     */
821    @Override
822    public void updateConsumerPrefetch(int newPrefetch) {
823        if (context != null && context.getConnection() != null && context.getConnection().isManageable()) {
824            ConsumerControl cc = new ConsumerControl();
825            cc.setConsumerId(info.getConsumerId());
826            cc.setPrefetch(newPrefetch);
827            context.getConnection().dispatchAsync(cc);
828        }
829    }
830
831    /**
832     * @param node
833     * @param message
834     * @return MessageDispatch
835     */
836    protected MessageDispatch createMessageDispatch(MessageReference node, Message message) {
837        MessageDispatch md = new MessageDispatch();
838        md.setConsumerId(info.getConsumerId());
839
840        if (node == QueueMessageReference.NULL_MESSAGE) {
841            md.setMessage(null);
842            md.setDestination(null);
843        } else {
844            Destination regionDestination = (Destination) node.getRegionDestination();
845            md.setDestination(regionDestination.getActiveMQDestination());
846            md.setMessage(message);
847            md.setRedeliveryCounter(node.getRedeliveryCounter());
848        }
849
850        return md;
851    }
852
853    /**
854     * Use when a matched message is about to be dispatched to the client.
855     *
856     * @param node
857     * @return false if the message should not be dispatched to the client
858     *         (another sub may have already dispatched it for example).
859     * @throws IOException
860     */
861    protected abstract boolean canDispatch(MessageReference node) throws IOException;
862
863    protected abstract boolean isDropped(MessageReference node);
864
865    /**
866     * Used during acknowledgment to remove the message.
867     *
868     * @throws IOException
869     */
870    protected abstract void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference node) throws IOException;
871
872
873    public int getMaxProducersToAudit() {
874        return maxProducersToAudit;
875    }
876
877    public void setMaxProducersToAudit(int maxProducersToAudit) {
878        this.maxProducersToAudit = maxProducersToAudit;
879        if (this.pending != null) {
880            this.pending.setMaxProducersToAudit(maxProducersToAudit);
881        }
882    }
883
884    public int getMaxAuditDepth() {
885        return maxAuditDepth;
886    }
887
888    public void setMaxAuditDepth(int maxAuditDepth) {
889        this.maxAuditDepth = maxAuditDepth;
890        if (this.pending != null) {
891            this.pending.setMaxAuditDepth(maxAuditDepth);
892        }
893    }
894
895    public boolean isUsePrefetchExtension() {
896        return usePrefetchExtension;
897    }
898
899    public void setUsePrefetchExtension(boolean usePrefetchExtension) {
900        this.usePrefetchExtension = usePrefetchExtension;
901    }
902
903    protected int getPrefetchExtension() {
904        return this.prefetchExtension.get();
905    }
906
907    @Override
908    public void setPrefetchSize(int prefetchSize) {
909        this.info.setPrefetchSize(prefetchSize);
910        try {
911            this.dispatchPending();
912        } catch (Exception e) {
913            LOG.trace("Caught exception during dispatch after prefetch change.", e);
914        }
915    }
916}