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