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