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