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.Collection;
022import java.util.Collections;
023import java.util.Comparator;
024import java.util.HashSet;
025import java.util.Iterator;
026import java.util.LinkedHashMap;
027import java.util.LinkedHashSet;
028import java.util.LinkedList;
029import java.util.List;
030import java.util.Map;
031import java.util.Set;
032import java.util.concurrent.CancellationException;
033import java.util.concurrent.ConcurrentLinkedQueue;
034import java.util.concurrent.CountDownLatch;
035import java.util.concurrent.DelayQueue;
036import java.util.concurrent.Delayed;
037import java.util.concurrent.ExecutorService;
038import java.util.concurrent.TimeUnit;
039import java.util.concurrent.atomic.AtomicBoolean;
040import java.util.concurrent.atomic.AtomicLong;
041import java.util.concurrent.locks.Lock;
042import java.util.concurrent.locks.ReentrantLock;
043import java.util.concurrent.locks.ReentrantReadWriteLock;
044
045import javax.jms.InvalidSelectorException;
046import javax.jms.JMSException;
047import javax.jms.ResourceAllocationException;
048
049import org.apache.activemq.broker.BrokerService;
050import org.apache.activemq.broker.ConnectionContext;
051import org.apache.activemq.broker.ProducerBrokerExchange;
052import org.apache.activemq.broker.region.cursors.OrderedPendingList;
053import org.apache.activemq.broker.region.cursors.PendingList;
054import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
055import org.apache.activemq.broker.region.cursors.PrioritizedPendingList;
056import org.apache.activemq.broker.region.cursors.QueueDispatchPendingList;
057import org.apache.activemq.broker.region.cursors.StoreQueueCursor;
058import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor;
059import org.apache.activemq.broker.region.group.CachedMessageGroupMapFactory;
060import org.apache.activemq.broker.region.group.MessageGroupMap;
061import org.apache.activemq.broker.region.group.MessageGroupMapFactory;
062import org.apache.activemq.broker.region.policy.DeadLetterStrategy;
063import org.apache.activemq.broker.region.policy.DispatchPolicy;
064import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy;
065import org.apache.activemq.broker.util.InsertionCountList;
066import org.apache.activemq.command.ActiveMQDestination;
067import org.apache.activemq.command.ConsumerId;
068import org.apache.activemq.command.ExceptionResponse;
069import org.apache.activemq.command.Message;
070import org.apache.activemq.command.MessageAck;
071import org.apache.activemq.command.MessageDispatchNotification;
072import org.apache.activemq.command.MessageId;
073import org.apache.activemq.command.ProducerAck;
074import org.apache.activemq.command.ProducerInfo;
075import org.apache.activemq.command.RemoveInfo;
076import org.apache.activemq.command.Response;
077import org.apache.activemq.filter.BooleanExpression;
078import org.apache.activemq.filter.MessageEvaluationContext;
079import org.apache.activemq.filter.NonCachedMessageEvaluationContext;
080import org.apache.activemq.selector.SelectorParser;
081import org.apache.activemq.state.ProducerState;
082import org.apache.activemq.store.IndexListener;
083import org.apache.activemq.store.ListenableFuture;
084import org.apache.activemq.store.MessageRecoveryListener;
085import org.apache.activemq.store.MessageStore;
086import org.apache.activemq.thread.Task;
087import org.apache.activemq.thread.TaskRunner;
088import org.apache.activemq.thread.TaskRunnerFactory;
089import org.apache.activemq.transaction.Synchronization;
090import org.apache.activemq.usage.Usage;
091import org.apache.activemq.usage.UsageListener;
092import org.apache.activemq.util.BrokerSupport;
093import org.apache.activemq.util.ThreadPoolUtils;
094import org.slf4j.Logger;
095import org.slf4j.LoggerFactory;
096import org.slf4j.MDC;
097
098import static org.apache.activemq.broker.region.cursors.AbstractStoreCursor.gotToTheStore;
099
100/**
101 * The Queue is a List of MessageEntry objects that are dispatched to matching
102 * subscriptions.
103 */
104public class Queue extends BaseDestination implements Task, UsageListener, IndexListener {
105    protected static final Logger LOG = LoggerFactory.getLogger(Queue.class);
106    protected final TaskRunnerFactory taskFactory;
107    protected TaskRunner taskRunner;
108    private final ReentrantReadWriteLock consumersLock = new ReentrantReadWriteLock();
109    protected final List<Subscription> consumers = new ArrayList<Subscription>(50);
110    private final ReentrantReadWriteLock messagesLock = new ReentrantReadWriteLock();
111    protected PendingMessageCursor messages;
112    private final ReentrantReadWriteLock pagedInMessagesLock = new ReentrantReadWriteLock();
113    private final PendingList pagedInMessages = new OrderedPendingList();
114    // Messages that are paged in but have not yet been targeted at a subscription
115    private final ReentrantReadWriteLock pagedInPendingDispatchLock = new ReentrantReadWriteLock();
116    protected QueueDispatchPendingList dispatchPendingList = new QueueDispatchPendingList();
117    private MessageGroupMap messageGroupOwners;
118    private DispatchPolicy dispatchPolicy = new RoundRobinDispatchPolicy();
119    private MessageGroupMapFactory messageGroupMapFactory = new CachedMessageGroupMapFactory();
120    final Lock sendLock = new ReentrantLock();
121    private ExecutorService executor;
122    private final Map<MessageId, Runnable> messagesWaitingForSpace = new LinkedHashMap<MessageId, Runnable>();
123    private boolean useConsumerPriority = true;
124    private boolean strictOrderDispatch = false;
125    private final QueueDispatchSelector dispatchSelector;
126    private boolean optimizedDispatch = false;
127    private boolean iterationRunning = false;
128    private boolean firstConsumer = false;
129    private int timeBeforeDispatchStarts = 0;
130    private int consumersBeforeDispatchStarts = 0;
131    private CountDownLatch consumersBeforeStartsLatch;
132    private final AtomicLong pendingWakeups = new AtomicLong();
133    private boolean allConsumersExclusiveByDefault = false;
134    private final AtomicBoolean started = new AtomicBoolean();
135
136    private boolean resetNeeded;
137
138    private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() {
139        @Override
140        public void run() {
141            asyncWakeup();
142        }
143    };
144    private final Runnable expireMessagesTask = new Runnable() {
145        @Override
146        public void run() {
147            expireMessages();
148        }
149    };
150
151    private final Object iteratingMutex = new Object();
152
153
154
155    class TimeoutMessage implements Delayed {
156
157        Message message;
158        ConnectionContext context;
159        long trigger;
160
161        public TimeoutMessage(Message message, ConnectionContext context, long delay) {
162            this.message = message;
163            this.context = context;
164            this.trigger = System.currentTimeMillis() + delay;
165        }
166
167        @Override
168        public long getDelay(TimeUnit unit) {
169            long n = trigger - System.currentTimeMillis();
170            return unit.convert(n, TimeUnit.MILLISECONDS);
171        }
172
173        @Override
174        public int compareTo(Delayed delayed) {
175            long other = ((TimeoutMessage) delayed).trigger;
176            int returnValue;
177            if (this.trigger < other) {
178                returnValue = -1;
179            } else if (this.trigger > other) {
180                returnValue = 1;
181            } else {
182                returnValue = 0;
183            }
184            return returnValue;
185        }
186    }
187
188    DelayQueue<TimeoutMessage> flowControlTimeoutMessages = new DelayQueue<TimeoutMessage>();
189
190    class FlowControlTimeoutTask extends Thread {
191
192        @Override
193        public void run() {
194            TimeoutMessage timeout;
195            try {
196                while (true) {
197                    timeout = flowControlTimeoutMessages.take();
198                    if (timeout != null) {
199                        synchronized (messagesWaitingForSpace) {
200                            if (messagesWaitingForSpace.remove(timeout.message.getMessageId()) != null) {
201                                ExceptionResponse response = new ExceptionResponse(
202                                        new ResourceAllocationException(
203                                                "Usage Manager Memory Limit reached. Stopping producer ("
204                                                        + timeout.message.getProducerId()
205                                                        + ") to prevent flooding "
206                                                        + getActiveMQDestination().getQualifiedName()
207                                                        + "."
208                                                        + " See http://activemq.apache.org/producer-flow-control.html for more info"));
209                                response.setCorrelationId(timeout.message.getCommandId());
210                                timeout.context.getConnection().dispatchAsync(response);
211                            }
212                        }
213                    }
214                }
215            } catch (InterruptedException e) {
216                LOG.debug(getName() + "Producer Flow Control Timeout Task is stopping");
217            }
218        }
219    };
220
221    private final FlowControlTimeoutTask flowControlTimeoutTask = new FlowControlTimeoutTask();
222
223    private final Comparator<Subscription> orderedCompare = new Comparator<Subscription>() {
224
225        @Override
226        public int compare(Subscription s1, Subscription s2) {
227            // We want the list sorted in descending order
228            int val = s2.getConsumerInfo().getPriority() - s1.getConsumerInfo().getPriority();
229            if (val == 0 && messageGroupOwners != null) {
230                // then ascending order of assigned message groups to favour less loaded consumers
231                // Long.compare in jdk7
232                long x = s1.getConsumerInfo().getAssignedGroupCount(destination);
233                long y = s2.getConsumerInfo().getAssignedGroupCount(destination);
234                val = (x < y) ? -1 : ((x == y) ? 0 : 1);
235            }
236            return val;
237        }
238    };
239
240    public Queue(BrokerService brokerService, final ActiveMQDestination destination, MessageStore store,
241            DestinationStatistics parentStats, TaskRunnerFactory taskFactory) throws Exception {
242        super(brokerService, store, destination, parentStats);
243        this.taskFactory = taskFactory;
244        this.dispatchSelector = new QueueDispatchSelector(destination);
245        if (store != null) {
246            store.registerIndexListener(this);
247        }
248    }
249
250    @Override
251    public List<Subscription> getConsumers() {
252        consumersLock.readLock().lock();
253        try {
254            return new ArrayList<Subscription>(consumers);
255        } finally {
256            consumersLock.readLock().unlock();
257        }
258    }
259
260    // make the queue easily visible in the debugger from its task runner
261    // threads
262    final class QueueThread extends Thread {
263        final Queue queue;
264
265        public QueueThread(Runnable runnable, String name, Queue queue) {
266            super(runnable, name);
267            this.queue = queue;
268        }
269    }
270
271    class BatchMessageRecoveryListener implements MessageRecoveryListener {
272        final LinkedList<Message> toExpire = new LinkedList<Message>();
273        final double totalMessageCount;
274        int recoveredAccumulator = 0;
275        int currentBatchCount;
276
277        BatchMessageRecoveryListener(int totalMessageCount) {
278            this.totalMessageCount = totalMessageCount;
279            currentBatchCount = recoveredAccumulator;
280        }
281
282        @Override
283        public boolean recoverMessage(Message message) {
284            recoveredAccumulator++;
285            if ((recoveredAccumulator % 10000) == 0) {
286                LOG.info("cursor for {} has recovered {} messages. {}% complete", new Object[]{ getActiveMQDestination().getQualifiedName(), recoveredAccumulator, new Integer((int) (recoveredAccumulator * 100 / totalMessageCount))});
287            }
288            // Message could have expired while it was being
289            // loaded..
290            message.setRegionDestination(Queue.this);
291            if (message.isExpired() && broker.isExpired(message)) {
292                toExpire.add(message);
293                return true;
294            }
295            if (hasSpace()) {
296                messagesLock.writeLock().lock();
297                try {
298                    try {
299                        messages.addMessageLast(message);
300                    } catch (Exception e) {
301                        LOG.error("Failed to add message to cursor", e);
302                    }
303                } finally {
304                    messagesLock.writeLock().unlock();
305                }
306                destinationStatistics.getMessages().increment();
307                return true;
308            }
309            return false;
310        }
311
312        @Override
313        public boolean recoverMessageReference(MessageId messageReference) throws Exception {
314            throw new RuntimeException("Should not be called.");
315        }
316
317        @Override
318        public boolean hasSpace() {
319            return true;
320        }
321
322        @Override
323        public boolean isDuplicate(MessageId id) {
324            return false;
325        }
326
327        public void reset() {
328            currentBatchCount = recoveredAccumulator;
329        }
330
331        public void processExpired() {
332            for (Message message: toExpire) {
333                messageExpired(createConnectionContext(), createMessageReference(message));
334                // drop message will decrement so counter
335                // balance here
336                destinationStatistics.getMessages().increment();
337            }
338            toExpire.clear();
339        }
340
341        public boolean done() {
342            return currentBatchCount == recoveredAccumulator;
343        }
344    }
345
346    @Override
347    public void setPrioritizedMessages(boolean prioritizedMessages) {
348        super.setPrioritizedMessages(prioritizedMessages);
349        dispatchPendingList.setPrioritizedMessages(prioritizedMessages);
350    }
351
352    @Override
353    public void initialize() throws Exception {
354
355        if (this.messages == null) {
356            if (destination.isTemporary() || broker == null || store == null) {
357                this.messages = new VMPendingMessageCursor(isPrioritizedMessages());
358            } else {
359                this.messages = new StoreQueueCursor(broker, this);
360            }
361        }
362
363        // If a VMPendingMessageCursor don't use the default Producer System
364        // Usage
365        // since it turns into a shared blocking queue which can lead to a
366        // network deadlock.
367        // If we are cursoring to disk..it's not and issue because it does not
368        // block due
369        // to large disk sizes.
370        if (messages instanceof VMPendingMessageCursor) {
371            this.systemUsage = brokerService.getSystemUsage();
372            memoryUsage.setParent(systemUsage.getMemoryUsage());
373        }
374
375        this.taskRunner = taskFactory.createTaskRunner(this, "Queue:" + destination.getPhysicalName());
376
377        super.initialize();
378        if (store != null) {
379            // Restore the persistent messages.
380            messages.setSystemUsage(systemUsage);
381            messages.setEnableAudit(isEnableAudit());
382            messages.setMaxAuditDepth(getMaxAuditDepth());
383            messages.setMaxProducersToAudit(getMaxProducersToAudit());
384            messages.setUseCache(isUseCache());
385            messages.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark());
386            final int messageCount = store.getMessageCount();
387            if (messageCount > 0 && messages.isRecoveryRequired()) {
388                BatchMessageRecoveryListener listener = new BatchMessageRecoveryListener(messageCount);
389                do {
390                   listener.reset();
391                   store.recoverNextMessages(getMaxPageSize(), listener);
392                   listener.processExpired();
393               } while (!listener.done());
394            } else {
395                destinationStatistics.getMessages().add(messageCount);
396            }
397        }
398    }
399
400    /*
401     * Holder for subscription that needs attention on next iterate browser
402     * needs access to existing messages in the queue that have already been
403     * dispatched
404     */
405    class BrowserDispatch {
406        QueueBrowserSubscription browser;
407
408        public BrowserDispatch(QueueBrowserSubscription browserSubscription) {
409            browser = browserSubscription;
410            browser.incrementQueueRef();
411        }
412
413        void done() {
414            try {
415                browser.decrementQueueRef();
416            } catch (Exception e) {
417                LOG.warn("decrement ref on browser: " + browser, e);
418            }
419        }
420
421        public QueueBrowserSubscription getBrowser() {
422            return browser;
423        }
424    }
425
426    ConcurrentLinkedQueue<BrowserDispatch> browserDispatches = new ConcurrentLinkedQueue<BrowserDispatch>();
427
428    @Override
429    public void addSubscription(ConnectionContext context, Subscription sub) throws Exception {
430        LOG.debug("{} add sub: {}, dequeues: {}, dispatched: {}, inflight: {}", new Object[]{ getActiveMQDestination().getQualifiedName(), sub, getDestinationStatistics().getDequeues().getCount(), getDestinationStatistics().getDispatched().getCount(), getDestinationStatistics().getInflight().getCount() });
431
432        super.addSubscription(context, sub);
433        // synchronize with dispatch method so that no new messages are sent
434        // while setting up a subscription. avoid out of order messages,
435        // duplicates, etc.
436        pagedInPendingDispatchLock.writeLock().lock();
437        try {
438
439            sub.add(context, this);
440
441            // needs to be synchronized - so no contention with dispatching
442            // consumersLock.
443            consumersLock.writeLock().lock();
444            try {
445                // set a flag if this is a first consumer
446                if (consumers.size() == 0) {
447                    firstConsumer = true;
448                    if (consumersBeforeDispatchStarts != 0) {
449                        consumersBeforeStartsLatch = new CountDownLatch(consumersBeforeDispatchStarts - 1);
450                    }
451                } else {
452                    if (consumersBeforeStartsLatch != null) {
453                        consumersBeforeStartsLatch.countDown();
454                    }
455                }
456
457                addToConsumerList(sub);
458                if (sub.getConsumerInfo().isExclusive() || isAllConsumersExclusiveByDefault()) {
459                    Subscription exclusiveConsumer = dispatchSelector.getExclusiveConsumer();
460                    if (exclusiveConsumer == null) {
461                        exclusiveConsumer = sub;
462                    } else if (sub.getConsumerInfo().getPriority() == Byte.MAX_VALUE ||
463                        sub.getConsumerInfo().getPriority() > exclusiveConsumer.getConsumerInfo().getPriority()) {
464                        exclusiveConsumer = sub;
465                    }
466                    dispatchSelector.setExclusiveConsumer(exclusiveConsumer);
467                }
468            } finally {
469                consumersLock.writeLock().unlock();
470            }
471
472            if (sub instanceof QueueBrowserSubscription) {
473                // tee up for dispatch in next iterate
474                QueueBrowserSubscription browserSubscription = (QueueBrowserSubscription) sub;
475                BrowserDispatch browserDispatch = new BrowserDispatch(browserSubscription);
476                browserDispatches.add(browserDispatch);
477            }
478
479            if (!this.optimizedDispatch) {
480                wakeup();
481            }
482        } finally {
483            pagedInPendingDispatchLock.writeLock().unlock();
484        }
485        if (this.optimizedDispatch) {
486            // Outside of dispatchLock() to maintain the lock hierarchy of
487            // iteratingMutex -> dispatchLock. - see
488            // https://issues.apache.org/activemq/browse/AMQ-1878
489            wakeup();
490        }
491    }
492
493    @Override
494    public void removeSubscription(ConnectionContext context, Subscription sub, long lastDeliveredSequenceId)
495            throws Exception {
496        super.removeSubscription(context, sub, lastDeliveredSequenceId);
497        // synchronize with dispatch method so that no new messages are sent
498        // while removing up a subscription.
499        pagedInPendingDispatchLock.writeLock().lock();
500        try {
501            LOG.debug("{} remove sub: {}, lastDeliveredSeqId: {}, dequeues: {}, dispatched: {}, inflight: {}, groups: {}", new Object[]{
502                    getActiveMQDestination().getQualifiedName(),
503                    sub,
504                    lastDeliveredSequenceId,
505                    getDestinationStatistics().getDequeues().getCount(),
506                    getDestinationStatistics().getDispatched().getCount(),
507                    getDestinationStatistics().getInflight().getCount(),
508                    sub.getConsumerInfo().getAssignedGroupCount(destination)
509            });
510            consumersLock.writeLock().lock();
511            try {
512                removeFromConsumerList(sub);
513                if (sub.getConsumerInfo().isExclusive()) {
514                    Subscription exclusiveConsumer = dispatchSelector.getExclusiveConsumer();
515                    if (exclusiveConsumer == sub) {
516                        exclusiveConsumer = null;
517                        for (Subscription s : consumers) {
518                            if (s.getConsumerInfo().isExclusive()
519                                    && (exclusiveConsumer == null || s.getConsumerInfo().getPriority() > exclusiveConsumer
520                                            .getConsumerInfo().getPriority())) {
521                                exclusiveConsumer = s;
522
523                            }
524                        }
525                        dispatchSelector.setExclusiveConsumer(exclusiveConsumer);
526                    }
527                } else if (isAllConsumersExclusiveByDefault()) {
528                    Subscription exclusiveConsumer = null;
529                    for (Subscription s : consumers) {
530                        if (exclusiveConsumer == null
531                                || s.getConsumerInfo().getPriority() > exclusiveConsumer
532                                .getConsumerInfo().getPriority()) {
533                            exclusiveConsumer = s;
534                                }
535                    }
536                    dispatchSelector.setExclusiveConsumer(exclusiveConsumer);
537                }
538                ConsumerId consumerId = sub.getConsumerInfo().getConsumerId();
539                getMessageGroupOwners().removeConsumer(consumerId);
540
541                // redeliver inflight messages
542
543                boolean markAsRedelivered = false;
544                MessageReference lastDeliveredRef = null;
545                List<MessageReference> unAckedMessages = sub.remove(context, this);
546
547                // locate last redelivered in unconsumed list (list in delivery rather than seq order)
548                if (lastDeliveredSequenceId > RemoveInfo.LAST_DELIVERED_UNSET) {
549                    for (MessageReference ref : unAckedMessages) {
550                        if (ref.getMessageId().getBrokerSequenceId() == lastDeliveredSequenceId) {
551                            lastDeliveredRef = ref;
552                            markAsRedelivered = true;
553                            LOG.debug("found lastDeliveredSeqID: {}, message reference: {}", lastDeliveredSequenceId, ref.getMessageId());
554                            break;
555                        }
556                    }
557                }
558
559                for (Iterator<MessageReference> unackedListIterator = unAckedMessages.iterator(); unackedListIterator.hasNext(); ) {
560                    MessageReference ref = unackedListIterator.next();
561                    // AMQ-5107: don't resend if the broker is shutting down
562                    if ( this.brokerService.isStopping() ) {
563                        break;
564                    }
565                    QueueMessageReference qmr = (QueueMessageReference) ref;
566                    if (qmr.getLockOwner() == sub) {
567                        qmr.unlock();
568
569                        // have no delivery information
570                        if (lastDeliveredSequenceId == RemoveInfo.LAST_DELIVERED_UNKNOWN) {
571                            qmr.incrementRedeliveryCounter();
572                        } else {
573                            if (markAsRedelivered) {
574                                qmr.incrementRedeliveryCounter();
575                            }
576                            if (ref == lastDeliveredRef) {
577                                // all that follow were not redelivered
578                                markAsRedelivered = false;
579                            }
580                        }
581                    }
582                    if (qmr.isDropped()) {
583                        unackedListIterator.remove();
584                    }
585                }
586                dispatchPendingList.addForRedelivery(unAckedMessages, strictOrderDispatch && consumers.isEmpty());
587                if (sub instanceof QueueBrowserSubscription) {
588                    ((QueueBrowserSubscription)sub).decrementQueueRef();
589                    browserDispatches.remove(sub);
590                }
591                // AMQ-5107: don't resend if the broker is shutting down
592                if (dispatchPendingList.hasRedeliveries() && (! this.brokerService.isStopping())) {
593                    doDispatch(new OrderedPendingList());
594                }
595            } finally {
596                consumersLock.writeLock().unlock();
597            }
598            if (!this.optimizedDispatch) {
599                wakeup();
600            }
601        } finally {
602            pagedInPendingDispatchLock.writeLock().unlock();
603        }
604        if (this.optimizedDispatch) {
605            // Outside of dispatchLock() to maintain the lock hierarchy of
606            // iteratingMutex -> dispatchLock. - see
607            // https://issues.apache.org/activemq/browse/AMQ-1878
608            wakeup();
609        }
610    }
611
612    @Override
613    public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception {
614        final ConnectionContext context = producerExchange.getConnectionContext();
615        // There is delay between the client sending it and it arriving at the
616        // destination.. it may have expired.
617        message.setRegionDestination(this);
618        ProducerState state = producerExchange.getProducerState();
619        if (state == null) {
620            LOG.warn("Send failed for: {}, missing producer state for: {}", message, producerExchange);
621            throw new JMSException("Cannot send message to " + getActiveMQDestination() + " with invalid (null) producer state");
622        }
623        final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo();
624        final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0
625                && !context.isInRecoveryMode();
626        if (message.isExpired()) {
627            // message not stored - or added to stats yet - so chuck here
628            broker.getRoot().messageExpired(context, message, null);
629            if (sendProducerAck) {
630                ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
631                context.getConnection().dispatchAsync(ack);
632            }
633            return;
634        }
635        if (memoryUsage.isFull()) {
636            isFull(context, memoryUsage);
637            fastProducer(context, producerInfo);
638            if (isProducerFlowControl() && context.isProducerFlowControl()) {
639                if (warnOnProducerFlowControl) {
640                    warnOnProducerFlowControl = false;
641                    LOG.info("Usage Manager Memory Limit ({}) reached on {}, size {}. Producers will be throttled to the rate at which messages are removed from this destination to prevent flooding it. See http://activemq.apache.org/producer-flow-control.html for more info.",
642                                    memoryUsage.getLimit(), getActiveMQDestination().getQualifiedName(), destinationStatistics.getMessages().getCount());
643                }
644
645                if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) {
646                    throw new ResourceAllocationException("Usage Manager Memory Limit reached. Stopping producer ("
647                            + message.getProducerId() + ") to prevent flooding "
648                            + getActiveMQDestination().getQualifiedName() + "."
649                            + " See http://activemq.apache.org/producer-flow-control.html for more info");
650                }
651
652                // We can avoid blocking due to low usage if the producer is
653                // sending
654                // a sync message or if it is using a producer window
655                if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) {
656                    // copy the exchange state since the context will be
657                    // modified while we are waiting
658                    // for space.
659                    final ProducerBrokerExchange producerExchangeCopy = producerExchange.copy();
660                    synchronized (messagesWaitingForSpace) {
661                     // Start flow control timeout task
662                        // Prevent trying to start it multiple times
663                        if (!flowControlTimeoutTask.isAlive()) {
664                            flowControlTimeoutTask.setName(getName()+" Producer Flow Control Timeout Task");
665                            flowControlTimeoutTask.start();
666                        }
667                        messagesWaitingForSpace.put(message.getMessageId(), new Runnable() {
668                            @Override
669                            public void run() {
670
671                                try {
672                                    // While waiting for space to free up... the
673                                    // message may have expired.
674                                    if (message.isExpired()) {
675                                        LOG.error("expired waiting for space..");
676                                        broker.messageExpired(context, message, null);
677                                        destinationStatistics.getExpired().increment();
678                                    } else {
679                                        doMessageSend(producerExchangeCopy, message);
680                                    }
681
682                                    if (sendProducerAck) {
683                                        ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message
684                                                .getSize());
685                                        context.getConnection().dispatchAsync(ack);
686                                    } else {
687                                        Response response = new Response();
688                                        response.setCorrelationId(message.getCommandId());
689                                        context.getConnection().dispatchAsync(response);
690                                    }
691
692                                } catch (Exception e) {
693                                    if (!sendProducerAck && !context.isInRecoveryMode() && !brokerService.isStopping()) {
694                                        ExceptionResponse response = new ExceptionResponse(e);
695                                        response.setCorrelationId(message.getCommandId());
696                                        context.getConnection().dispatchAsync(response);
697                                    } else {
698                                        LOG.debug("unexpected exception on deferred send of: {}", message, e);
699                                    }
700                                }
701                            }
702                        });
703
704                        if (!context.isNetworkConnection() && systemUsage.getSendFailIfNoSpaceAfterTimeout() != 0) {
705                            flowControlTimeoutMessages.add(new TimeoutMessage(message, context, systemUsage
706                                    .getSendFailIfNoSpaceAfterTimeout()));
707                        }
708
709                        registerCallbackForNotFullNotification();
710                        context.setDontSendReponse(true);
711                        return;
712                    }
713
714                } else {
715
716                    if (memoryUsage.isFull()) {
717                        waitForSpace(context, producerExchange, memoryUsage, "Usage Manager Memory Limit reached. Producer ("
718                                + message.getProducerId() + ") stopped to prevent flooding "
719                                + getActiveMQDestination().getQualifiedName() + "."
720                                + " See http://activemq.apache.org/producer-flow-control.html for more info");
721                    }
722
723                    // The usage manager could have delayed us by the time
724                    // we unblock the message could have expired..
725                    if (message.isExpired()) {
726                        LOG.debug("Expired message: {}", message);
727                        broker.getRoot().messageExpired(context, message, null);
728                        return;
729                    }
730                }
731            }
732        }
733        doMessageSend(producerExchange, message);
734        if (sendProducerAck) {
735            ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
736            context.getConnection().dispatchAsync(ack);
737        }
738    }
739
740    private void registerCallbackForNotFullNotification() {
741        // If the usage manager is not full, then the task will not
742        // get called..
743        if (!memoryUsage.notifyCallbackWhenNotFull(sendMessagesWaitingForSpaceTask)) {
744            // so call it directly here.
745            sendMessagesWaitingForSpaceTask.run();
746        }
747    }
748
749    private final LinkedList<MessageContext> indexOrderedCursorUpdates = new LinkedList<>();
750
751    @Override
752    public void onAdd(MessageContext messageContext) {
753        synchronized (indexOrderedCursorUpdates) {
754            indexOrderedCursorUpdates.addLast(messageContext);
755        }
756    }
757
758    private void doPendingCursorAdditions() throws Exception {
759        LinkedList<MessageContext> orderedUpdates = new LinkedList<>();
760        sendLock.lockInterruptibly();
761        try {
762            synchronized (indexOrderedCursorUpdates) {
763                MessageContext candidate = indexOrderedCursorUpdates.peek();
764                while (candidate != null && candidate.message.getMessageId().getFutureOrSequenceLong() != null) {
765                    candidate = indexOrderedCursorUpdates.removeFirst();
766                    // check for duplicate adds suppressed by the store
767                    if (candidate.message.getMessageId().getFutureOrSequenceLong() instanceof Long && ((Long)candidate.message.getMessageId().getFutureOrSequenceLong()).compareTo(-1l) == 0) {
768                        LOG.warn("{} messageStore indicated duplicate add attempt for {}, suppressing duplicate dispatch", this, candidate.message.getMessageId());
769                    } else {
770                        orderedUpdates.add(candidate);
771                    }
772                    candidate = indexOrderedCursorUpdates.peek();
773                }
774            }
775            messagesLock.writeLock().lock();
776            try {
777                for (MessageContext messageContext : orderedUpdates) {
778                    if (!messages.addMessageLast(messageContext.message)) {
779                        // cursor suppressed a duplicate
780                        messageContext.duplicate = true;
781                    }
782                    if (messageContext.onCompletion != null) {
783                        messageContext.onCompletion.run();
784                    }
785                }
786            } finally {
787                messagesLock.writeLock().unlock();
788            }
789        } finally {
790            sendLock.unlock();
791        }
792        for (MessageContext messageContext : orderedUpdates) {
793            if (!messageContext.duplicate) {
794                messageSent(messageContext.context, messageContext.message);
795            }
796        }
797        orderedUpdates.clear();
798    }
799
800    final class CursorAddSync extends Synchronization {
801
802        private final MessageContext messageContext;
803
804        CursorAddSync(MessageContext messageContext) {
805            this.messageContext = messageContext;
806            this.messageContext.message.incrementReferenceCount();
807        }
808
809        @Override
810        public void afterCommit() throws Exception {
811            if (store != null && messageContext.message.isPersistent()) {
812                doPendingCursorAdditions();
813            } else {
814                cursorAdd(messageContext.message);
815                messageSent(messageContext.context, messageContext.message);
816            }
817            messageContext.message.decrementReferenceCount();
818        }
819
820        @Override
821        public void afterRollback() throws Exception {
822            messageContext.message.decrementReferenceCount();
823        }
824    }
825
826    void doMessageSend(final ProducerBrokerExchange producerExchange, final Message message) throws IOException,
827            Exception {
828        final ConnectionContext context = producerExchange.getConnectionContext();
829        ListenableFuture<Object> result = null;
830
831        producerExchange.incrementSend();
832        checkUsage(context, producerExchange, message);
833        message.getMessageId().setBrokerSequenceId(getDestinationSequenceId());
834        if (store != null && message.isPersistent()) {
835            message.getMessageId().setFutureOrSequenceLong(null);
836            try {
837                //AMQ-6133 - don't store async if using persistJMSRedelivered
838                //This flag causes a sync update later on dispatch which can cause a race
839                //condition if the original add is processed after the update, which can cause
840                //a duplicate message to be stored
841                if (messages.isCacheEnabled() && !isPersistJMSRedelivered()) {
842                    result = store.asyncAddQueueMessage(context, message, isOptimizeStorage());
843                    result.addListener(new PendingMarshalUsageTracker(message));
844                } else {
845                    store.addMessage(context, message);
846                }
847                if (isReduceMemoryFootprint()) {
848                    message.clearMarshalledState();
849                }
850            } catch (Exception e) {
851                // we may have a store in inconsistent state, so reset the cursor
852                // before restarting normal broker operations
853                resetNeeded = true;
854                throw e;
855            }
856        }
857        orderedCursorAdd(message, context);
858        if (result != null && message.isResponseRequired() && !result.isCancelled()) {
859            try {
860                result.get();
861            } catch (CancellationException e) {
862                // ignore - the task has been cancelled if the message
863                // has already been deleted
864            }
865        }
866    }
867
868    private void orderedCursorAdd(Message message, ConnectionContext context) throws Exception {
869        if (context.isInTransaction()) {
870            context.getTransaction().addSynchronization(new CursorAddSync(new MessageContext(context, message, null)));
871        } else if (store != null && message.isPersistent()) {
872            doPendingCursorAdditions();
873        } else {
874            // no ordering issue with non persistent messages
875            cursorAdd(message);
876            messageSent(context, message);
877        }
878    }
879
880    private void checkUsage(ConnectionContext context,ProducerBrokerExchange producerBrokerExchange, Message message) throws ResourceAllocationException, IOException, InterruptedException {
881        if (message.isPersistent()) {
882            if (store != null && systemUsage.getStoreUsage().isFull(getStoreUsageHighWaterMark())) {
883                final String logMessage = "Persistent store is Full, " + getStoreUsageHighWaterMark() + "% of "
884                    + systemUsage.getStoreUsage().getLimit() + ". Stopping producer ("
885                    + message.getProducerId() + ") to prevent flooding "
886                    + getActiveMQDestination().getQualifiedName() + "."
887                    + " See http://activemq.apache.org/producer-flow-control.html for more info";
888
889                waitForSpace(context, producerBrokerExchange, systemUsage.getStoreUsage(), getStoreUsageHighWaterMark(), logMessage);
890            }
891        } else if (messages.getSystemUsage() != null && systemUsage.getTempUsage().isFull()) {
892            final String logMessage = "Temp Store is Full ("
893                    + systemUsage.getTempUsage().getPercentUsage() + "% of " + systemUsage.getTempUsage().getLimit()
894                    +"). Stopping producer (" + message.getProducerId()
895                + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "."
896                + " See http://activemq.apache.org/producer-flow-control.html for more info";
897
898            waitForSpace(context, producerBrokerExchange, messages.getSystemUsage().getTempUsage(), logMessage);
899        }
900    }
901
902    private void expireMessages() {
903        LOG.debug("{} expiring messages ..", getActiveMQDestination().getQualifiedName());
904
905        // just track the insertion count
906        List<Message> browsedMessages = new InsertionCountList<Message>();
907        doBrowse(browsedMessages, this.getMaxExpirePageSize());
908        asyncWakeup();
909        LOG.debug("{} expiring messages done.", getActiveMQDestination().getQualifiedName());
910    }
911
912    @Override
913    public void gc() {
914    }
915
916    @Override
917    public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node)
918            throws IOException {
919        messageConsumed(context, node);
920        if (store != null && node.isPersistent()) {
921            store.removeAsyncMessage(context, convertToNonRangedAck(ack, node));
922        }
923    }
924
925    Message loadMessage(MessageId messageId) throws IOException {
926        Message msg = null;
927        if (store != null) { // can be null for a temp q
928            msg = store.getMessage(messageId);
929            if (msg != null) {
930                msg.setRegionDestination(this);
931            }
932        }
933        return msg;
934    }
935
936    @Override
937    public String toString() {
938        return destination.getQualifiedName() + ", subscriptions=" + consumers.size()
939                + ", memory=" + memoryUsage.getPercentUsage() + "%, size=" + destinationStatistics.getMessages().getCount() + ", pending="
940                + indexOrderedCursorUpdates.size();
941    }
942
943    @Override
944    public void start() throws Exception {
945        if (started.compareAndSet(false, true)) {
946            if (memoryUsage != null) {
947                memoryUsage.start();
948            }
949            if (systemUsage.getStoreUsage() != null) {
950                systemUsage.getStoreUsage().start();
951            }
952            systemUsage.getMemoryUsage().addUsageListener(this);
953            messages.start();
954            if (getExpireMessagesPeriod() > 0) {
955                scheduler.executePeriodically(expireMessagesTask, getExpireMessagesPeriod());
956            }
957            doPageIn(false);
958        }
959    }
960
961    @Override
962    public void stop() throws Exception {
963        if (started.compareAndSet(true, false)) {
964            if (taskRunner != null) {
965                taskRunner.shutdown();
966            }
967            if (this.executor != null) {
968                ThreadPoolUtils.shutdownNow(executor);
969                executor = null;
970            }
971
972            scheduler.cancel(expireMessagesTask);
973
974            if (flowControlTimeoutTask.isAlive()) {
975                flowControlTimeoutTask.interrupt();
976            }
977
978            if (messages != null) {
979                messages.stop();
980            }
981
982            for (MessageReference messageReference : pagedInMessages.values()) {
983                messageReference.decrementReferenceCount();
984            }
985            pagedInMessages.clear();
986
987            systemUsage.getMemoryUsage().removeUsageListener(this);
988            if (memoryUsage != null) {
989                memoryUsage.stop();
990            }
991            if (store != null) {
992                store.stop();
993            }
994        }
995    }
996
997    // Properties
998    // -------------------------------------------------------------------------
999    @Override
1000    public ActiveMQDestination getActiveMQDestination() {
1001        return destination;
1002    }
1003
1004    public MessageGroupMap getMessageGroupOwners() {
1005        if (messageGroupOwners == null) {
1006            messageGroupOwners = getMessageGroupMapFactory().createMessageGroupMap();
1007            messageGroupOwners.setDestination(this);
1008        }
1009        return messageGroupOwners;
1010    }
1011
1012    public DispatchPolicy getDispatchPolicy() {
1013        return dispatchPolicy;
1014    }
1015
1016    public void setDispatchPolicy(DispatchPolicy dispatchPolicy) {
1017        this.dispatchPolicy = dispatchPolicy;
1018    }
1019
1020    public MessageGroupMapFactory getMessageGroupMapFactory() {
1021        return messageGroupMapFactory;
1022    }
1023
1024    public void setMessageGroupMapFactory(MessageGroupMapFactory messageGroupMapFactory) {
1025        this.messageGroupMapFactory = messageGroupMapFactory;
1026    }
1027
1028    public PendingMessageCursor getMessages() {
1029        return this.messages;
1030    }
1031
1032    public void setMessages(PendingMessageCursor messages) {
1033        this.messages = messages;
1034    }
1035
1036    public boolean isUseConsumerPriority() {
1037        return useConsumerPriority;
1038    }
1039
1040    public void setUseConsumerPriority(boolean useConsumerPriority) {
1041        this.useConsumerPriority = useConsumerPriority;
1042    }
1043
1044    public boolean isStrictOrderDispatch() {
1045        return strictOrderDispatch;
1046    }
1047
1048    public void setStrictOrderDispatch(boolean strictOrderDispatch) {
1049        this.strictOrderDispatch = strictOrderDispatch;
1050    }
1051
1052    public boolean isOptimizedDispatch() {
1053        return optimizedDispatch;
1054    }
1055
1056    public void setOptimizedDispatch(boolean optimizedDispatch) {
1057        this.optimizedDispatch = optimizedDispatch;
1058    }
1059
1060    public int getTimeBeforeDispatchStarts() {
1061        return timeBeforeDispatchStarts;
1062    }
1063
1064    public void setTimeBeforeDispatchStarts(int timeBeforeDispatchStarts) {
1065        this.timeBeforeDispatchStarts = timeBeforeDispatchStarts;
1066    }
1067
1068    public int getConsumersBeforeDispatchStarts() {
1069        return consumersBeforeDispatchStarts;
1070    }
1071
1072    public void setConsumersBeforeDispatchStarts(int consumersBeforeDispatchStarts) {
1073        this.consumersBeforeDispatchStarts = consumersBeforeDispatchStarts;
1074    }
1075
1076    public void setAllConsumersExclusiveByDefault(boolean allConsumersExclusiveByDefault) {
1077        this.allConsumersExclusiveByDefault = allConsumersExclusiveByDefault;
1078    }
1079
1080    public boolean isAllConsumersExclusiveByDefault() {
1081        return allConsumersExclusiveByDefault;
1082    }
1083
1084    public boolean isResetNeeded() {
1085        return resetNeeded;
1086    }
1087
1088    // Implementation methods
1089    // -------------------------------------------------------------------------
1090    private QueueMessageReference createMessageReference(Message message) {
1091        QueueMessageReference result = new IndirectMessageReference(message);
1092        return result;
1093    }
1094
1095    @Override
1096    public Message[] browse() {
1097        List<Message> browseList = new ArrayList<Message>();
1098        doBrowse(browseList, getMaxBrowsePageSize());
1099        return browseList.toArray(new Message[browseList.size()]);
1100    }
1101
1102    public void doBrowse(List<Message> browseList, int max) {
1103        final ConnectionContext connectionContext = createConnectionContext();
1104        try {
1105            int maxPageInAttempts = 1;
1106            if (max > 0) {
1107                messagesLock.readLock().lock();
1108                try {
1109                    maxPageInAttempts += (messages.size() / max);
1110                } finally {
1111                    messagesLock.readLock().unlock();
1112                }
1113                while (shouldPageInMoreForBrowse(max) && maxPageInAttempts-- > 0) {
1114                    pageInMessages(!memoryUsage.isFull(110), max);
1115                }
1116            }
1117            doBrowseList(browseList, max, dispatchPendingList, pagedInPendingDispatchLock, connectionContext, "redeliveredWaitingDispatch+pagedInPendingDispatch");
1118            doBrowseList(browseList, max, pagedInMessages, pagedInMessagesLock, connectionContext, "pagedInMessages");
1119
1120            // we need a store iterator to walk messages on disk, independent of the cursor which is tracking
1121            // the next message batch
1122        } catch (Exception e) {
1123            LOG.error("Problem retrieving message for browse", e);
1124        }
1125    }
1126
1127    protected void doBrowseList(List<Message> browseList, int max, PendingList list, ReentrantReadWriteLock lock, ConnectionContext connectionContext, String name) throws Exception {
1128        List<MessageReference> toExpire = new ArrayList<MessageReference>();
1129        lock.readLock().lock();
1130        try {
1131            addAll(list.values(), browseList, max, toExpire);
1132        } finally {
1133            lock.readLock().unlock();
1134        }
1135        for (MessageReference ref : toExpire) {
1136            if (broker.isExpired(ref)) {
1137                LOG.debug("expiring from {}: {}", name, ref);
1138                messageExpired(connectionContext, ref);
1139            } else {
1140                lock.writeLock().lock();
1141                try {
1142                    list.remove(ref);
1143                } finally {
1144                    lock.writeLock().unlock();
1145                }
1146                ref.decrementReferenceCount();
1147            }
1148        }
1149    }
1150
1151    private boolean shouldPageInMoreForBrowse(int max) {
1152        int alreadyPagedIn = 0;
1153        pagedInMessagesLock.readLock().lock();
1154        try {
1155            alreadyPagedIn = pagedInMessages.size();
1156        } finally {
1157            pagedInMessagesLock.readLock().unlock();
1158        }
1159        int messagesInQueue = alreadyPagedIn;
1160        messagesLock.readLock().lock();
1161        try {
1162            messagesInQueue += messages.size();
1163        } finally {
1164            messagesLock.readLock().unlock();
1165        }
1166
1167        LOG.trace("max {}, alreadyPagedIn {}, messagesCount {}, memoryUsage {}%", new Object[]{max, alreadyPagedIn, messagesInQueue, memoryUsage.getPercentUsage()});
1168        return (alreadyPagedIn < max)
1169                && (alreadyPagedIn < messagesInQueue)
1170                && messages.hasSpace();
1171    }
1172
1173    private void addAll(Collection<? extends MessageReference> refs, List<Message> l, int max,
1174            List<MessageReference> toExpire) throws Exception {
1175        for (Iterator<? extends MessageReference> i = refs.iterator(); i.hasNext() && l.size() < max;) {
1176            QueueMessageReference ref = (QueueMessageReference) i.next();
1177            if (ref.isExpired() && (ref.getLockOwner() == null)) {
1178                toExpire.add(ref);
1179            } else if (l.contains(ref.getMessage()) == false) {
1180                l.add(ref.getMessage());
1181            }
1182        }
1183    }
1184
1185    public QueueMessageReference getMessage(String id) {
1186        MessageId msgId = new MessageId(id);
1187        pagedInMessagesLock.readLock().lock();
1188        try {
1189            QueueMessageReference ref = (QueueMessageReference)this.pagedInMessages.get(msgId);
1190            if (ref != null) {
1191                return ref;
1192            }
1193        } finally {
1194            pagedInMessagesLock.readLock().unlock();
1195        }
1196        messagesLock.writeLock().lock();
1197        try{
1198            try {
1199                messages.reset();
1200                while (messages.hasNext()) {
1201                    MessageReference mr = messages.next();
1202                    QueueMessageReference qmr = createMessageReference(mr.getMessage());
1203                    qmr.decrementReferenceCount();
1204                    messages.rollback(qmr.getMessageId());
1205                    if (msgId.equals(qmr.getMessageId())) {
1206                        return qmr;
1207                    }
1208                }
1209            } finally {
1210                messages.release();
1211            }
1212        }finally {
1213            messagesLock.writeLock().unlock();
1214        }
1215        return null;
1216    }
1217
1218    public void purge() throws Exception {
1219        ConnectionContext c = createConnectionContext();
1220        List<MessageReference> list = null;
1221        long originalMessageCount = this.destinationStatistics.getMessages().getCount();
1222        do {
1223            doPageIn(true, false, getMaxPageSize());  // signal no expiry processing needed.
1224            pagedInMessagesLock.readLock().lock();
1225            try {
1226                list = new ArrayList<MessageReference>(pagedInMessages.values());
1227            }finally {
1228                pagedInMessagesLock.readLock().unlock();
1229            }
1230
1231            for (MessageReference ref : list) {
1232                try {
1233                    QueueMessageReference r = (QueueMessageReference) ref;
1234                    removeMessage(c, r);
1235                } catch (IOException e) {
1236                }
1237            }
1238            // don't spin/hang if stats are out and there is nothing left in the
1239            // store
1240        } while (!list.isEmpty() && this.destinationStatistics.getMessages().getCount() > 0);
1241
1242        if (this.destinationStatistics.getMessages().getCount() > 0) {
1243            LOG.warn("{} after purge of {} messages, message count stats report: {}", getActiveMQDestination().getQualifiedName(), originalMessageCount, this.destinationStatistics.getMessages().getCount());
1244        }
1245        gc();
1246        this.destinationStatistics.getMessages().setCount(0);
1247        getMessages().clear();
1248    }
1249
1250    @Override
1251    public void clearPendingMessages() {
1252        messagesLock.writeLock().lock();
1253        try {
1254            if (resetNeeded) {
1255                messages.gc();
1256                messages.reset();
1257                resetNeeded = false;
1258            } else {
1259                messages.rebase();
1260            }
1261            asyncWakeup();
1262        } finally {
1263            messagesLock.writeLock().unlock();
1264        }
1265    }
1266
1267    /**
1268     * Removes the message matching the given messageId
1269     */
1270    public boolean removeMessage(String messageId) throws Exception {
1271        return removeMatchingMessages(createMessageIdFilter(messageId), 1) > 0;
1272    }
1273
1274    /**
1275     * Removes the messages matching the given selector
1276     *
1277     * @return the number of messages removed
1278     */
1279    public int removeMatchingMessages(String selector) throws Exception {
1280        return removeMatchingMessages(selector, -1);
1281    }
1282
1283    /**
1284     * Removes the messages matching the given selector up to the maximum number
1285     * of matched messages
1286     *
1287     * @return the number of messages removed
1288     */
1289    public int removeMatchingMessages(String selector, int maximumMessages) throws Exception {
1290        return removeMatchingMessages(createSelectorFilter(selector), maximumMessages);
1291    }
1292
1293    /**
1294     * Removes the messages matching the given filter up to the maximum number
1295     * of matched messages
1296     *
1297     * @return the number of messages removed
1298     */
1299    public int removeMatchingMessages(MessageReferenceFilter filter, int maximumMessages) throws Exception {
1300        int movedCounter = 0;
1301        Set<MessageReference> set = new LinkedHashSet<MessageReference>();
1302        ConnectionContext context = createConnectionContext();
1303        do {
1304            doPageIn(true);
1305            pagedInMessagesLock.readLock().lock();
1306            try {
1307                set.addAll(pagedInMessages.values());
1308            } finally {
1309                pagedInMessagesLock.readLock().unlock();
1310            }
1311            List<MessageReference> list = new ArrayList<MessageReference>(set);
1312            for (MessageReference ref : list) {
1313                IndirectMessageReference r = (IndirectMessageReference) ref;
1314                if (filter.evaluate(context, r)) {
1315
1316                    removeMessage(context, r);
1317                    set.remove(r);
1318                    if (++movedCounter >= maximumMessages && maximumMessages > 0) {
1319                        return movedCounter;
1320                    }
1321                }
1322            }
1323        } while (set.size() < this.destinationStatistics.getMessages().getCount());
1324        return movedCounter;
1325    }
1326
1327    /**
1328     * Copies the message matching the given messageId
1329     */
1330    public boolean copyMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest)
1331            throws Exception {
1332        return copyMatchingMessages(context, createMessageIdFilter(messageId), dest, 1) > 0;
1333    }
1334
1335    /**
1336     * Copies the messages matching the given selector
1337     *
1338     * @return the number of messages copied
1339     */
1340    public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest)
1341            throws Exception {
1342        return copyMatchingMessagesTo(context, selector, dest, -1);
1343    }
1344
1345    /**
1346     * Copies the messages matching the given selector up to the maximum number
1347     * of matched messages
1348     *
1349     * @return the number of messages copied
1350     */
1351    public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest,
1352            int maximumMessages) throws Exception {
1353        return copyMatchingMessages(context, createSelectorFilter(selector), dest, maximumMessages);
1354    }
1355
1356    /**
1357     * Copies the messages matching the given filter up to the maximum number of
1358     * matched messages
1359     *
1360     * @return the number of messages copied
1361     */
1362    public int copyMatchingMessages(ConnectionContext context, MessageReferenceFilter filter, ActiveMQDestination dest,
1363            int maximumMessages) throws Exception {
1364        int movedCounter = 0;
1365        int count = 0;
1366        Set<MessageReference> set = new LinkedHashSet<MessageReference>();
1367        do {
1368            int oldMaxSize = getMaxPageSize();
1369            setMaxPageSize((int) this.destinationStatistics.getMessages().getCount());
1370            doPageIn(true);
1371            setMaxPageSize(oldMaxSize);
1372            pagedInMessagesLock.readLock().lock();
1373            try {
1374                set.addAll(pagedInMessages.values());
1375            } finally {
1376                pagedInMessagesLock.readLock().unlock();
1377            }
1378            List<MessageReference> list = new ArrayList<MessageReference>(set);
1379            for (MessageReference ref : list) {
1380                IndirectMessageReference r = (IndirectMessageReference) ref;
1381                if (filter.evaluate(context, r)) {
1382
1383                    r.incrementReferenceCount();
1384                    try {
1385                        Message m = r.getMessage();
1386                        BrokerSupport.resend(context, m, dest);
1387                        if (++movedCounter >= maximumMessages && maximumMessages > 0) {
1388                            return movedCounter;
1389                        }
1390                    } finally {
1391                        r.decrementReferenceCount();
1392                    }
1393                }
1394                count++;
1395            }
1396        } while (count < this.destinationStatistics.getMessages().getCount());
1397        return movedCounter;
1398    }
1399
1400    /**
1401     * Move a message
1402     *
1403     * @param context
1404     *            connection context
1405     * @param m
1406     *            QueueMessageReference
1407     * @param dest
1408     *            ActiveMQDestination
1409     * @throws Exception
1410     */
1411    public boolean moveMessageTo(ConnectionContext context, QueueMessageReference m, ActiveMQDestination dest) throws Exception {
1412        BrokerSupport.resend(context, m.getMessage(), dest);
1413        removeMessage(context, m);
1414        messagesLock.writeLock().lock();
1415        try {
1416            messages.rollback(m.getMessageId());
1417            if (isDLQ()) {
1418                DeadLetterStrategy stratagy = getDeadLetterStrategy();
1419                stratagy.rollback(m.getMessage());
1420            }
1421        } finally {
1422            messagesLock.writeLock().unlock();
1423        }
1424        return true;
1425    }
1426
1427    /**
1428     * Moves the message matching the given messageId
1429     */
1430    public boolean moveMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest)
1431            throws Exception {
1432        return moveMatchingMessagesTo(context, createMessageIdFilter(messageId), dest, 1) > 0;
1433    }
1434
1435    /**
1436     * Moves the messages matching the given selector
1437     *
1438     * @return the number of messages removed
1439     */
1440    public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest)
1441            throws Exception {
1442        return moveMatchingMessagesTo(context, selector, dest, Integer.MAX_VALUE);
1443    }
1444
1445    /**
1446     * Moves the messages matching the given selector up to the maximum number
1447     * of matched messages
1448     */
1449    public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest,
1450            int maximumMessages) throws Exception {
1451        return moveMatchingMessagesTo(context, createSelectorFilter(selector), dest, maximumMessages);
1452    }
1453
1454    /**
1455     * Moves the messages matching the given filter up to the maximum number of
1456     * matched messages
1457     */
1458    public int moveMatchingMessagesTo(ConnectionContext context, MessageReferenceFilter filter,
1459            ActiveMQDestination dest, int maximumMessages) throws Exception {
1460        int movedCounter = 0;
1461        Set<MessageReference> set = new LinkedHashSet<MessageReference>();
1462        do {
1463            doPageIn(true);
1464            pagedInMessagesLock.readLock().lock();
1465            try {
1466                set.addAll(pagedInMessages.values());
1467            } finally {
1468                pagedInMessagesLock.readLock().unlock();
1469            }
1470            List<MessageReference> list = new ArrayList<MessageReference>(set);
1471            for (MessageReference ref : list) {
1472                if (filter.evaluate(context, ref)) {
1473                    // We should only move messages that can be locked.
1474                    moveMessageTo(context, (QueueMessageReference)ref, dest);
1475                    set.remove(ref);
1476                    if (++movedCounter >= maximumMessages && maximumMessages > 0) {
1477                        return movedCounter;
1478                    }
1479                }
1480            }
1481        } while (set.size() < this.destinationStatistics.getMessages().getCount() && set.size() < maximumMessages);
1482        return movedCounter;
1483    }
1484
1485    public int retryMessages(ConnectionContext context, int maximumMessages) throws Exception {
1486        if (!isDLQ()) {
1487            throw new Exception("Retry of message is only possible on Dead Letter Queues!");
1488        }
1489        int restoredCounter = 0;
1490        Set<MessageReference> set = new LinkedHashSet<MessageReference>();
1491        do {
1492            doPageIn(true);
1493            pagedInMessagesLock.readLock().lock();
1494            try {
1495                set.addAll(pagedInMessages.values());
1496            } finally {
1497                pagedInMessagesLock.readLock().unlock();
1498            }
1499            List<MessageReference> list = new ArrayList<MessageReference>(set);
1500            for (MessageReference ref : list) {
1501                if (ref.getMessage().getOriginalDestination() != null) {
1502
1503                    moveMessageTo(context, (QueueMessageReference)ref, ref.getMessage().getOriginalDestination());
1504                    set.remove(ref);
1505                    if (++restoredCounter >= maximumMessages && maximumMessages > 0) {
1506                        return restoredCounter;
1507                    }
1508                }
1509            }
1510        } while (set.size() < this.destinationStatistics.getMessages().getCount() && set.size() < maximumMessages);
1511        return restoredCounter;
1512    }
1513
1514    /**
1515     * @return true if we would like to iterate again
1516     * @see org.apache.activemq.thread.Task#iterate()
1517     */
1518    @Override
1519    public boolean iterate() {
1520        MDC.put("activemq.destination", getName());
1521        boolean pageInMoreMessages = false;
1522        synchronized (iteratingMutex) {
1523
1524            // If optimize dispatch is on or this is a slave this method could be called recursively
1525            // we set this state value to short-circuit wakeup in those cases to avoid that as it
1526            // could lead to errors.
1527            iterationRunning = true;
1528
1529            // do early to allow dispatch of these waiting messages
1530            synchronized (messagesWaitingForSpace) {
1531                Iterator<Runnable> it = messagesWaitingForSpace.values().iterator();
1532                while (it.hasNext()) {
1533                    if (!memoryUsage.isFull()) {
1534                        Runnable op = it.next();
1535                        it.remove();
1536                        op.run();
1537                    } else {
1538                        registerCallbackForNotFullNotification();
1539                        break;
1540                    }
1541                }
1542            }
1543
1544            if (firstConsumer) {
1545                firstConsumer = false;
1546                try {
1547                    if (consumersBeforeDispatchStarts > 0) {
1548                        int timeout = 1000; // wait one second by default if
1549                                            // consumer count isn't reached
1550                        if (timeBeforeDispatchStarts > 0) {
1551                            timeout = timeBeforeDispatchStarts;
1552                        }
1553                        if (consumersBeforeStartsLatch.await(timeout, TimeUnit.MILLISECONDS)) {
1554                            LOG.debug("{} consumers subscribed. Starting dispatch.", consumers.size());
1555                        } else {
1556                            LOG.debug("{} ms elapsed and {} consumers subscribed. Starting dispatch.", timeout, consumers.size());
1557                        }
1558                    }
1559                    if (timeBeforeDispatchStarts > 0 && consumersBeforeDispatchStarts <= 0) {
1560                        iteratingMutex.wait(timeBeforeDispatchStarts);
1561                        LOG.debug("{} ms elapsed. Starting dispatch.", timeBeforeDispatchStarts);
1562                    }
1563                } catch (Exception e) {
1564                    LOG.error(e.toString());
1565                }
1566            }
1567
1568            messagesLock.readLock().lock();
1569            try{
1570                pageInMoreMessages |= !messages.isEmpty();
1571            } finally {
1572                messagesLock.readLock().unlock();
1573            }
1574
1575            pagedInPendingDispatchLock.readLock().lock();
1576            try {
1577                pageInMoreMessages |= !dispatchPendingList.isEmpty();
1578            } finally {
1579                pagedInPendingDispatchLock.readLock().unlock();
1580            }
1581
1582            // Perhaps we should page always into the pagedInPendingDispatch
1583            // list if
1584            // !messages.isEmpty(), and then if
1585            // !pagedInPendingDispatch.isEmpty()
1586            // then we do a dispatch.
1587            boolean hasBrowsers = browserDispatches.size() > 0;
1588
1589            if (pageInMoreMessages || hasBrowsers || !dispatchPendingList.hasRedeliveries()) {
1590                try {
1591                    pageInMessages(hasBrowsers && getMaxBrowsePageSize() > 0, getMaxPageSize());
1592                } catch (Throwable e) {
1593                    LOG.error("Failed to page in more queue messages ", e);
1594                }
1595            }
1596
1597            if (hasBrowsers) {
1598                PendingList alreadyDispatchedMessages = isPrioritizedMessages() ?
1599                        new PrioritizedPendingList() : new OrderedPendingList();
1600                pagedInMessagesLock.readLock().lock();
1601                try{
1602                    alreadyDispatchedMessages.addAll(pagedInMessages);
1603                }finally {
1604                    pagedInMessagesLock.readLock().unlock();
1605                }
1606
1607                Iterator<BrowserDispatch> browsers = browserDispatches.iterator();
1608                while (browsers.hasNext()) {
1609                    BrowserDispatch browserDispatch = browsers.next();
1610                    try {
1611                        MessageEvaluationContext msgContext = new NonCachedMessageEvaluationContext();
1612                        msgContext.setDestination(destination);
1613
1614                        QueueBrowserSubscription browser = browserDispatch.getBrowser();
1615
1616                        LOG.debug("dispatch to browser: {}, already dispatched/paged count: {}", browser, alreadyDispatchedMessages.size());
1617                        boolean added = false;
1618                        for (MessageReference node : alreadyDispatchedMessages) {
1619                            if (!((QueueMessageReference)node).isAcked() && !browser.isDuplicate(node.getMessageId()) && !browser.atMax()) {
1620                                msgContext.setMessageReference(node);
1621                                if (browser.matches(node, msgContext)) {
1622                                    browser.add(node);
1623                                    added = true;
1624                                }
1625                            }
1626                        }
1627                        // are we done browsing? no new messages paged
1628                        if (!added || browser.atMax()) {
1629                            browser.decrementQueueRef();
1630                            browserDispatches.remove(browserDispatch);
1631                        }
1632                    } catch (Exception e) {
1633                        LOG.warn("exception on dispatch to browser: {}", browserDispatch.getBrowser(), e);
1634                    }
1635                }
1636            }
1637
1638            if (pendingWakeups.get() > 0) {
1639                pendingWakeups.decrementAndGet();
1640            }
1641            MDC.remove("activemq.destination");
1642            iterationRunning = false;
1643
1644            return pendingWakeups.get() > 0;
1645        }
1646    }
1647
1648    public void pauseDispatch() {
1649        dispatchSelector.pause();
1650    }
1651
1652    public void resumeDispatch() {
1653        dispatchSelector.resume();
1654        wakeup();
1655    }
1656
1657    public boolean isDispatchPaused() {
1658        return dispatchSelector.isPaused();
1659    }
1660
1661    protected MessageReferenceFilter createMessageIdFilter(final String messageId) {
1662        return new MessageReferenceFilter() {
1663            @Override
1664            public boolean evaluate(ConnectionContext context, MessageReference r) {
1665                return messageId.equals(r.getMessageId().toString());
1666            }
1667
1668            @Override
1669            public String toString() {
1670                return "MessageIdFilter: " + messageId;
1671            }
1672        };
1673    }
1674
1675    protected MessageReferenceFilter createSelectorFilter(String selector) throws InvalidSelectorException {
1676
1677        if (selector == null || selector.isEmpty()) {
1678            return new MessageReferenceFilter() {
1679
1680                @Override
1681                public boolean evaluate(ConnectionContext context, MessageReference messageReference) throws JMSException {
1682                    return true;
1683                }
1684            };
1685        }
1686
1687        final BooleanExpression selectorExpression = SelectorParser.parse(selector);
1688
1689        return new MessageReferenceFilter() {
1690            @Override
1691            public boolean evaluate(ConnectionContext context, MessageReference r) throws JMSException {
1692                MessageEvaluationContext messageEvaluationContext = context.getMessageEvaluationContext();
1693
1694                messageEvaluationContext.setMessageReference(r);
1695                if (messageEvaluationContext.getDestination() == null) {
1696                    messageEvaluationContext.setDestination(getActiveMQDestination());
1697                }
1698
1699                return selectorExpression.matches(messageEvaluationContext);
1700            }
1701        };
1702    }
1703
1704    protected void removeMessage(ConnectionContext c, QueueMessageReference r) throws IOException {
1705        removeMessage(c, null, r);
1706        pagedInPendingDispatchLock.writeLock().lock();
1707        try {
1708            dispatchPendingList.remove(r);
1709        } finally {
1710            pagedInPendingDispatchLock.writeLock().unlock();
1711        }
1712    }
1713
1714    protected void removeMessage(ConnectionContext c, Subscription subs, QueueMessageReference r) throws IOException {
1715        MessageAck ack = new MessageAck();
1716        ack.setAckType(MessageAck.STANDARD_ACK_TYPE);
1717        ack.setDestination(destination);
1718        ack.setMessageID(r.getMessageId());
1719        removeMessage(c, subs, r, ack);
1720    }
1721
1722    protected void removeMessage(ConnectionContext context, Subscription sub, final QueueMessageReference reference,
1723            MessageAck ack) throws IOException {
1724        LOG.trace("ack of {} with {}", reference.getMessageId(), ack);
1725        // This sends the ack the the journal..
1726        if (!ack.isInTransaction()) {
1727            acknowledge(context, sub, ack, reference);
1728            getDestinationStatistics().getDequeues().increment();
1729            dropMessage(reference);
1730        } else {
1731            try {
1732                acknowledge(context, sub, ack, reference);
1733            } finally {
1734                context.getTransaction().addSynchronization(new Synchronization() {
1735
1736                    @Override
1737                    public void afterCommit() throws Exception {
1738                        getDestinationStatistics().getDequeues().increment();
1739                        dropMessage(reference);
1740                        wakeup();
1741                    }
1742
1743                    @Override
1744                    public void afterRollback() throws Exception {
1745                        reference.setAcked(false);
1746                        wakeup();
1747                    }
1748                });
1749            }
1750        }
1751        if (ack.isPoisonAck() || (sub != null && sub.getConsumerInfo().isNetworkSubscription())) {
1752            // message gone to DLQ, is ok to allow redelivery
1753            messagesLock.writeLock().lock();
1754            try {
1755                messages.rollback(reference.getMessageId());
1756            } finally {
1757                messagesLock.writeLock().unlock();
1758            }
1759            if (sub != null && sub.getConsumerInfo().isNetworkSubscription()) {
1760                getDestinationStatistics().getForwards().increment();
1761            }
1762        }
1763        // after successful store update
1764        reference.setAcked(true);
1765    }
1766
1767    private void dropMessage(QueueMessageReference reference) {
1768        if (!reference.isDropped()) {
1769            reference.drop();
1770            destinationStatistics.getMessages().decrement();
1771            pagedInMessagesLock.writeLock().lock();
1772            try {
1773                pagedInMessages.remove(reference);
1774            } finally {
1775                pagedInMessagesLock.writeLock().unlock();
1776            }
1777        }
1778    }
1779
1780    public void messageExpired(ConnectionContext context, MessageReference reference) {
1781        messageExpired(context, null, reference);
1782    }
1783
1784    @Override
1785    public void messageExpired(ConnectionContext context, Subscription subs, MessageReference reference) {
1786        LOG.debug("message expired: {}", reference);
1787        broker.messageExpired(context, reference, subs);
1788        destinationStatistics.getExpired().increment();
1789        try {
1790            removeMessage(context, subs, (QueueMessageReference) reference);
1791            messagesLock.writeLock().lock();
1792            try {
1793                messages.rollback(reference.getMessageId());
1794            } finally {
1795                messagesLock.writeLock().unlock();
1796            }
1797        } catch (IOException e) {
1798            LOG.error("Failed to remove expired Message from the store ", e);
1799        }
1800    }
1801
1802    final boolean cursorAdd(final Message msg) throws Exception {
1803        messagesLock.writeLock().lock();
1804        try {
1805            return messages.addMessageLast(msg);
1806        } finally {
1807            messagesLock.writeLock().unlock();
1808        }
1809    }
1810
1811    final void messageSent(final ConnectionContext context, final Message msg) throws Exception {
1812        destinationStatistics.getEnqueues().increment();
1813        destinationStatistics.getMessages().increment();
1814        destinationStatistics.getMessageSize().addSize(msg.getSize());
1815        messageDelivered(context, msg);
1816        consumersLock.readLock().lock();
1817        try {
1818            if (consumers.isEmpty()) {
1819                onMessageWithNoConsumers(context, msg);
1820            }
1821        }finally {
1822            consumersLock.readLock().unlock();
1823        }
1824        LOG.debug("{} Message {} sent to {}", new Object[]{ broker.getBrokerName(), msg.getMessageId(), this.destination });
1825        wakeup();
1826    }
1827
1828    @Override
1829    public void wakeup() {
1830        if (optimizedDispatch && !iterationRunning) {
1831            iterate();
1832            pendingWakeups.incrementAndGet();
1833        } else {
1834            asyncWakeup();
1835        }
1836    }
1837
1838    private void asyncWakeup() {
1839        try {
1840            pendingWakeups.incrementAndGet();
1841            this.taskRunner.wakeup();
1842        } catch (InterruptedException e) {
1843            LOG.warn("Async task runner failed to wakeup ", e);
1844        }
1845    }
1846
1847    private void doPageIn(boolean force) throws Exception {
1848        doPageIn(force, true, getMaxPageSize());
1849    }
1850
1851    private void doPageIn(boolean force, boolean processExpired, int maxPageSize) throws Exception {
1852        PendingList newlyPaged = doPageInForDispatch(force, processExpired, maxPageSize);
1853        pagedInPendingDispatchLock.writeLock().lock();
1854        try {
1855            if (dispatchPendingList.isEmpty()) {
1856                dispatchPendingList.addAll(newlyPaged);
1857
1858            } else {
1859                for (MessageReference qmr : newlyPaged) {
1860                    if (!dispatchPendingList.contains(qmr)) {
1861                        dispatchPendingList.addMessageLast(qmr);
1862                    }
1863                }
1864            }
1865        } finally {
1866            pagedInPendingDispatchLock.writeLock().unlock();
1867        }
1868    }
1869
1870    private PendingList doPageInForDispatch(boolean force, boolean processExpired, int maxPageSize) throws Exception {
1871        List<QueueMessageReference> result = null;
1872        PendingList resultList = null;
1873
1874        int toPageIn = Math.min(maxPageSize, messages.size());
1875        int pagedInPendingSize = 0;
1876        pagedInPendingDispatchLock.readLock().lock();
1877        try {
1878            pagedInPendingSize = dispatchPendingList.size();
1879        } finally {
1880            pagedInPendingDispatchLock.readLock().unlock();
1881        }
1882        if (isLazyDispatch() && !force) {
1883            // Only page in the minimum number of messages which can be
1884            // dispatched immediately.
1885            toPageIn = Math.min(getConsumerMessageCountBeforeFull(), toPageIn);
1886        }
1887
1888        if (LOG.isDebugEnabled()) {
1889            LOG.debug("{} toPageIn: {}, force:{}, Inflight: {}, pagedInMessages.size {}, pagedInPendingDispatch.size {}, enqueueCount: {}, dequeueCount: {}, memUsage:{}, maxPageSize:{}",
1890                    new Object[]{
1891                            this,
1892                            toPageIn,
1893                            force,
1894                            destinationStatistics.getInflight().getCount(),
1895                            pagedInMessages.size(),
1896                            pagedInPendingSize,
1897                            destinationStatistics.getEnqueues().getCount(),
1898                            destinationStatistics.getDequeues().getCount(),
1899                            getMemoryUsage().getUsage(),
1900                            maxPageSize
1901                    });
1902        }
1903
1904        if (toPageIn > 0 && (force || (haveRealConsumer() && pagedInPendingSize < maxPageSize))) {
1905            int count = 0;
1906            result = new ArrayList<QueueMessageReference>(toPageIn);
1907            messagesLock.writeLock().lock();
1908            try {
1909                try {
1910                    messages.setMaxBatchSize(toPageIn);
1911                    messages.reset();
1912                    while (count < toPageIn && messages.hasNext()) {
1913                        MessageReference node = messages.next();
1914                        messages.remove();
1915
1916                        QueueMessageReference ref = createMessageReference(node.getMessage());
1917                        if (processExpired && ref.isExpired()) {
1918                            if (broker.isExpired(ref)) {
1919                                messageExpired(createConnectionContext(), ref);
1920                            } else {
1921                                ref.decrementReferenceCount();
1922                            }
1923                        } else {
1924                            result.add(ref);
1925                            count++;
1926                        }
1927                    }
1928                } finally {
1929                    messages.release();
1930                }
1931            } finally {
1932                messagesLock.writeLock().unlock();
1933            }
1934            // Only add new messages, not already pagedIn to avoid multiple
1935            // dispatch attempts
1936            pagedInMessagesLock.writeLock().lock();
1937            try {
1938                if(isPrioritizedMessages()) {
1939                    resultList = new PrioritizedPendingList();
1940                } else {
1941                    resultList = new OrderedPendingList();
1942                }
1943                for (QueueMessageReference ref : result) {
1944                    if (!pagedInMessages.contains(ref)) {
1945                        pagedInMessages.addMessageLast(ref);
1946                        resultList.addMessageLast(ref);
1947                    } else {
1948                        ref.decrementReferenceCount();
1949                        // store should have trapped duplicate in it's index, or cursor audit trapped insert
1950                        // or producerBrokerExchange suppressed send.
1951                        // note: jdbc store will not trap unacked messages as a duplicate b/c it gives each message a unique sequence id
1952                        LOG.warn("{}, duplicate message {} from cursor, is cursor audit disabled or too constrained? Redirecting to dlq", this, ref.getMessage());
1953                        if (store != null) {
1954                            ConnectionContext connectionContext = createConnectionContext();
1955                            dropMessage(ref);
1956                            if (gotToTheStore(ref.getMessage())) {
1957                                LOG.debug("Duplicate message {} from cursor, removing from store", this, ref.getMessage());
1958                                store.removeMessage(connectionContext, new MessageAck(ref.getMessage(), MessageAck.POSION_ACK_TYPE, 1));
1959                            }
1960                            broker.getRoot().sendToDeadLetterQueue(connectionContext, ref.getMessage(), null, new Throwable("duplicate paged in from cursor for " + destination));
1961                        }
1962                    }
1963                }
1964            } finally {
1965                pagedInMessagesLock.writeLock().unlock();
1966            }
1967        } else {
1968            // Avoid return null list, if condition is not validated
1969            resultList = new OrderedPendingList();
1970        }
1971
1972        return resultList;
1973    }
1974
1975    private final boolean haveRealConsumer() {
1976        return consumers.size() - browserDispatches.size() > 0;
1977    }
1978
1979    private void doDispatch(PendingList list) throws Exception {
1980        boolean doWakeUp = false;
1981
1982        pagedInPendingDispatchLock.writeLock().lock();
1983        try {
1984            if (isPrioritizedMessages() && !dispatchPendingList.isEmpty() && list != null && !list.isEmpty()) {
1985                // merge all to select priority order
1986                for (MessageReference qmr : list) {
1987                    if (!dispatchPendingList.contains(qmr)) {
1988                        dispatchPendingList.addMessageLast(qmr);
1989                    }
1990                }
1991                list = null;
1992            }
1993
1994            doActualDispatch(dispatchPendingList);
1995            // and now see if we can dispatch the new stuff.. and append to the pending
1996            // list anything that does not actually get dispatched.
1997            if (list != null && !list.isEmpty()) {
1998                if (dispatchPendingList.isEmpty()) {
1999                    dispatchPendingList.addAll(doActualDispatch(list));
2000                } else {
2001                    for (MessageReference qmr : list) {
2002                        if (!dispatchPendingList.contains(qmr)) {
2003                            dispatchPendingList.addMessageLast(qmr);
2004                        }
2005                    }
2006                    doWakeUp = true;
2007                }
2008            }
2009        } finally {
2010            pagedInPendingDispatchLock.writeLock().unlock();
2011        }
2012
2013        if (doWakeUp) {
2014            // avoid lock order contention
2015            asyncWakeup();
2016        }
2017    }
2018
2019    /**
2020     * @return list of messages that could get dispatched to consumers if they
2021     *         were not full.
2022     */
2023    private PendingList doActualDispatch(PendingList list) throws Exception {
2024        List<Subscription> consumers;
2025        consumersLock.readLock().lock();
2026
2027        try {
2028            if (this.consumers.isEmpty()) {
2029                // slave dispatch happens in processDispatchNotification
2030                return list;
2031            }
2032            consumers = new ArrayList<Subscription>(this.consumers);
2033        } finally {
2034            consumersLock.readLock().unlock();
2035        }
2036
2037        Set<Subscription> fullConsumers = new HashSet<Subscription>(this.consumers.size());
2038
2039        for (Iterator<MessageReference> iterator = list.iterator(); iterator.hasNext();) {
2040
2041            MessageReference node = iterator.next();
2042            Subscription target = null;
2043            for (Subscription s : consumers) {
2044                if (s instanceof QueueBrowserSubscription) {
2045                    continue;
2046                }
2047                if (!fullConsumers.contains(s)) {
2048                    if (!s.isFull()) {
2049                        if (dispatchSelector.canSelect(s, node) && assignMessageGroup(s, (QueueMessageReference)node) && !((QueueMessageReference) node).isAcked() ) {
2050                            // Dispatch it.
2051                            s.add(node);
2052                            LOG.trace("assigned {} to consumer {}", node.getMessageId(), s.getConsumerInfo().getConsumerId());
2053                            iterator.remove();
2054                            target = s;
2055                            break;
2056                        }
2057                    } else {
2058                        // no further dispatch of list to a full consumer to
2059                        // avoid out of order message receipt
2060                        fullConsumers.add(s);
2061                        LOG.trace("Subscription full {}", s);
2062                    }
2063                }
2064            }
2065
2066            if (target == null && node.isDropped()) {
2067                iterator.remove();
2068            }
2069
2070            // return if there are no consumers or all consumers are full
2071            if (target == null && consumers.size() == fullConsumers.size()) {
2072                return list;
2073            }
2074
2075            // If it got dispatched, rotate the consumer list to get round robin
2076            // distribution.
2077            if (target != null && !strictOrderDispatch && consumers.size() > 1
2078                    && !dispatchSelector.isExclusiveConsumer(target)) {
2079                consumersLock.writeLock().lock();
2080                try {
2081                    if (removeFromConsumerList(target)) {
2082                        addToConsumerList(target);
2083                        consumers = new ArrayList<Subscription>(this.consumers);
2084                    }
2085                } finally {
2086                    consumersLock.writeLock().unlock();
2087                }
2088            }
2089        }
2090
2091        return list;
2092    }
2093
2094    protected boolean assignMessageGroup(Subscription subscription, QueueMessageReference node) throws Exception {
2095        boolean result = true;
2096        // Keep message groups together.
2097        String groupId = node.getGroupID();
2098        int sequence = node.getGroupSequence();
2099        if (groupId != null) {
2100
2101            MessageGroupMap messageGroupOwners = getMessageGroupOwners();
2102            // If we can own the first, then no-one else should own the
2103            // rest.
2104            if (sequence == 1) {
2105                assignGroup(subscription, messageGroupOwners, node, groupId);
2106            } else {
2107
2108                // Make sure that the previous owner is still valid, we may
2109                // need to become the new owner.
2110                ConsumerId groupOwner;
2111
2112                groupOwner = messageGroupOwners.get(groupId);
2113                if (groupOwner == null) {
2114                    assignGroup(subscription, messageGroupOwners, node, groupId);
2115                } else {
2116                    if (groupOwner.equals(subscription.getConsumerInfo().getConsumerId())) {
2117                        // A group sequence < 1 is an end of group signal.
2118                        if (sequence < 0) {
2119                            messageGroupOwners.removeGroup(groupId);
2120                            subscription.getConsumerInfo().decrementAssignedGroupCount(destination);
2121                        }
2122                    } else {
2123                        result = false;
2124                    }
2125                }
2126            }
2127        }
2128
2129        return result;
2130    }
2131
2132    protected void assignGroup(Subscription subs, MessageGroupMap messageGroupOwners, MessageReference n, String groupId) throws IOException {
2133        messageGroupOwners.put(groupId, subs.getConsumerInfo().getConsumerId());
2134        Message message = n.getMessage();
2135        message.setJMSXGroupFirstForConsumer(true);
2136        subs.getConsumerInfo().incrementAssignedGroupCount(destination);
2137    }
2138
2139    protected void pageInMessages(boolean force, int maxPageSize) throws Exception {
2140        doDispatch(doPageInForDispatch(force, true, maxPageSize));
2141    }
2142
2143    private void addToConsumerList(Subscription sub) {
2144        if (useConsumerPriority) {
2145            consumers.add(sub);
2146            Collections.sort(consumers, orderedCompare);
2147        } else {
2148            consumers.add(sub);
2149        }
2150    }
2151
2152    private boolean removeFromConsumerList(Subscription sub) {
2153        return consumers.remove(sub);
2154    }
2155
2156    private int getConsumerMessageCountBeforeFull() throws Exception {
2157        int total = 0;
2158        consumersLock.readLock().lock();
2159        try {
2160            for (Subscription s : consumers) {
2161                if (s.isBrowser()) {
2162                    continue;
2163                }
2164                int countBeforeFull = s.countBeforeFull();
2165                total += countBeforeFull;
2166            }
2167        } finally {
2168            consumersLock.readLock().unlock();
2169        }
2170        return total;
2171    }
2172
2173    /*
2174     * In slave mode, dispatch is ignored till we get this notification as the
2175     * dispatch process is non deterministic between master and slave. On a
2176     * notification, the actual dispatch to the subscription (as chosen by the
2177     * master) is completed. (non-Javadoc)
2178     * @see
2179     * org.apache.activemq.broker.region.BaseDestination#processDispatchNotification
2180     * (org.apache.activemq.command.MessageDispatchNotification)
2181     */
2182    @Override
2183    public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception {
2184        // do dispatch
2185        Subscription sub = getMatchingSubscription(messageDispatchNotification);
2186        if (sub != null) {
2187            MessageReference message = getMatchingMessage(messageDispatchNotification);
2188            sub.add(message);
2189            sub.processMessageDispatchNotification(messageDispatchNotification);
2190        }
2191    }
2192
2193    private QueueMessageReference getMatchingMessage(MessageDispatchNotification messageDispatchNotification)
2194            throws Exception {
2195        QueueMessageReference message = null;
2196        MessageId messageId = messageDispatchNotification.getMessageId();
2197
2198        pagedInPendingDispatchLock.writeLock().lock();
2199        try {
2200            for (MessageReference ref : dispatchPendingList) {
2201                if (messageId.equals(ref.getMessageId())) {
2202                    message = (QueueMessageReference)ref;
2203                    dispatchPendingList.remove(ref);
2204                    break;
2205                }
2206            }
2207        } finally {
2208            pagedInPendingDispatchLock.writeLock().unlock();
2209        }
2210
2211        if (message == null) {
2212            pagedInMessagesLock.readLock().lock();
2213            try {
2214                message = (QueueMessageReference)pagedInMessages.get(messageId);
2215            } finally {
2216                pagedInMessagesLock.readLock().unlock();
2217            }
2218        }
2219
2220        if (message == null) {
2221            messagesLock.writeLock().lock();
2222            try {
2223                try {
2224                    messages.setMaxBatchSize(getMaxPageSize());
2225                    messages.reset();
2226                    while (messages.hasNext()) {
2227                        MessageReference node = messages.next();
2228                        messages.remove();
2229                        if (messageId.equals(node.getMessageId())) {
2230                            message = this.createMessageReference(node.getMessage());
2231                            break;
2232                        }
2233                    }
2234                } finally {
2235                    messages.release();
2236                }
2237            } finally {
2238                messagesLock.writeLock().unlock();
2239            }
2240        }
2241
2242        if (message == null) {
2243            Message msg = loadMessage(messageId);
2244            if (msg != null) {
2245                message = this.createMessageReference(msg);
2246            }
2247        }
2248
2249        if (message == null) {
2250            throw new JMSException("Slave broker out of sync with master - Message: "
2251                    + messageDispatchNotification.getMessageId() + " on "
2252                    + messageDispatchNotification.getDestination() + " does not exist among pending("
2253                    + dispatchPendingList.size() + ") for subscription: "
2254                    + messageDispatchNotification.getConsumerId());
2255        }
2256        return message;
2257    }
2258
2259    /**
2260     * Find a consumer that matches the id in the message dispatch notification
2261     *
2262     * @param messageDispatchNotification
2263     * @return sub or null if the subscription has been removed before dispatch
2264     * @throws JMSException
2265     */
2266    private Subscription getMatchingSubscription(MessageDispatchNotification messageDispatchNotification)
2267            throws JMSException {
2268        Subscription sub = null;
2269        consumersLock.readLock().lock();
2270        try {
2271            for (Subscription s : consumers) {
2272                if (messageDispatchNotification.getConsumerId().equals(s.getConsumerInfo().getConsumerId())) {
2273                    sub = s;
2274                    break;
2275                }
2276            }
2277        } finally {
2278            consumersLock.readLock().unlock();
2279        }
2280        return sub;
2281    }
2282
2283    @Override
2284    public void onUsageChanged(@SuppressWarnings("rawtypes") Usage usage, int oldPercentUsage, int newPercentUsage) {
2285        if (oldPercentUsage > newPercentUsage) {
2286            asyncWakeup();
2287        }
2288    }
2289
2290    @Override
2291    protected Logger getLog() {
2292        return LOG;
2293    }
2294
2295    protected boolean isOptimizeStorage(){
2296        boolean result = false;
2297        if (isDoOptimzeMessageStorage()){
2298            consumersLock.readLock().lock();
2299            try{
2300                if (consumers.isEmpty()==false){
2301                    result = true;
2302                    for (Subscription s : consumers) {
2303                        if (s.getPrefetchSize()==0){
2304                            result = false;
2305                            break;
2306                        }
2307                        if (s.isSlowConsumer()){
2308                            result = false;
2309                            break;
2310                        }
2311                        if (s.getInFlightUsage() > getOptimizeMessageStoreInFlightLimit()){
2312                            result = false;
2313                            break;
2314                        }
2315                    }
2316                }
2317            } finally {
2318                consumersLock.readLock().unlock();
2319            }
2320        }
2321        return result;
2322    }
2323}