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