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