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