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