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