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