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