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;
018
019import java.io.IOException;
020import java.util.ArrayList;
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.Iterator;
024import java.util.LinkedList;
025import java.util.List;
026import java.util.Map;
027import java.util.Map.Entry;
028import java.util.concurrent.ExecutorService;
029import java.util.concurrent.Executors;
030import java.util.concurrent.atomic.AtomicBoolean;
031import java.util.concurrent.atomic.AtomicInteger;
032import java.util.concurrent.atomic.AtomicReference;
033
034import javax.jms.IllegalStateException;
035import javax.jms.InvalidDestinationException;
036import javax.jms.JMSException;
037import javax.jms.Message;
038import javax.jms.MessageConsumer;
039import javax.jms.MessageListener;
040import javax.jms.TransactionRolledBackException;
041
042import org.apache.activemq.blob.BlobDownloader;
043import org.apache.activemq.command.ActiveMQBlobMessage;
044import org.apache.activemq.command.ActiveMQDestination;
045import org.apache.activemq.command.ActiveMQMessage;
046import org.apache.activemq.command.ActiveMQObjectMessage;
047import org.apache.activemq.command.ActiveMQTempDestination;
048import org.apache.activemq.command.CommandTypes;
049import org.apache.activemq.command.ConsumerId;
050import org.apache.activemq.command.ConsumerInfo;
051import org.apache.activemq.command.MessageAck;
052import org.apache.activemq.command.MessageDispatch;
053import org.apache.activemq.command.MessageId;
054import org.apache.activemq.command.MessagePull;
055import org.apache.activemq.command.RemoveInfo;
056import org.apache.activemq.command.TransactionId;
057import org.apache.activemq.management.JMSConsumerStatsImpl;
058import org.apache.activemq.management.StatsCapable;
059import org.apache.activemq.management.StatsImpl;
060import org.apache.activemq.selector.SelectorParser;
061import org.apache.activemq.transaction.Synchronization;
062import org.apache.activemq.util.Callback;
063import org.apache.activemq.util.IntrospectionSupport;
064import org.apache.activemq.util.JMSExceptionSupport;
065import org.apache.activemq.util.ThreadPoolUtils;
066import org.slf4j.Logger;
067import org.slf4j.LoggerFactory;
068
069/**
070 * A client uses a <CODE>MessageConsumer</CODE> object to receive messages
071 * from a destination. A <CODE> MessageConsumer</CODE> object is created by
072 * passing a <CODE>Destination</CODE> object to a message-consumer creation
073 * method supplied by a session.
074 * <P>
075 * <CODE>MessageConsumer</CODE> is the parent interface for all message
076 * consumers.
077 * <P>
078 * A message consumer can be created with a message selector. A message selector
079 * allows the client to restrict the messages delivered to the message consumer
080 * to those that match the selector.
081 * <P>
082 * A client may either synchronously receive a message consumer's messages or
083 * have the consumer asynchronously deliver them as they arrive.
084 * <P>
085 * For synchronous receipt, a client can request the next message from a message
086 * consumer using one of its <CODE> receive</CODE> methods. There are several
087 * variations of <CODE>receive</CODE> that allow a client to poll or wait for
088 * the next message.
089 * <P>
090 * For asynchronous delivery, a client can register a
091 * <CODE>MessageListener</CODE> object with a message consumer. As messages
092 * arrive at the message consumer, it delivers them by calling the
093 * <CODE>MessageListener</CODE>'s<CODE>
094 * onMessage</CODE> method.
095 * <P>
096 * It is a client programming error for a <CODE>MessageListener</CODE> to
097 * throw an exception.
098 *
099 *
100 * @see javax.jms.MessageConsumer
101 * @see javax.jms.QueueReceiver
102 * @see javax.jms.TopicSubscriber
103 * @see javax.jms.Session
104 */
105public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsCapable, ActiveMQDispatcher {
106
107    @SuppressWarnings("serial")
108    class PreviouslyDeliveredMap<K, V> extends HashMap<K, V> {
109        final TransactionId transactionId;
110        public PreviouslyDeliveredMap(TransactionId transactionId) {
111            this.transactionId = transactionId;
112        }
113    }
114
115    private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageConsumer.class);
116    protected final ActiveMQSession session;
117    protected final ConsumerInfo info;
118
119    // These are the messages waiting to be delivered to the client
120    protected final MessageDispatchChannel unconsumedMessages;
121
122    // The are the messages that were delivered to the consumer but that have
123    // not been acknowledged. It's kept in reverse order since we
124    // Always walk list in reverse order.
125    protected final LinkedList<MessageDispatch> deliveredMessages = new LinkedList<MessageDispatch>();
126    // track duplicate deliveries in a transaction such that the tx integrity can be validated
127    private PreviouslyDeliveredMap<MessageId, Boolean> previouslyDeliveredMessages;
128    private int deliveredCounter;
129    private int additionalWindowSize;
130    private long redeliveryDelay;
131    private int ackCounter;
132    private int dispatchedCount;
133    private final AtomicReference<MessageListener> messageListener = new AtomicReference<MessageListener>();
134    private final JMSConsumerStatsImpl stats;
135
136    private final String selector;
137    private boolean synchronizationRegistered;
138    private final AtomicBoolean started = new AtomicBoolean(false);
139
140    private MessageAvailableListener availableListener;
141
142    private RedeliveryPolicy redeliveryPolicy;
143    private boolean optimizeAcknowledge;
144    private final AtomicBoolean deliveryingAcknowledgements = new AtomicBoolean();
145    private ExecutorService executorService;
146    private MessageTransformer transformer;
147    private boolean clearDeliveredList;
148    AtomicInteger inProgressClearRequiredFlag = new AtomicInteger(0);
149
150    private MessageAck pendingAck;
151    private long lastDeliveredSequenceId = -1;
152
153    private IOException failureError;
154
155    private long optimizeAckTimestamp = System.currentTimeMillis();
156    private long optimizeAcknowledgeTimeOut = 0;
157    private long optimizedAckScheduledAckInterval = 0;
158    private Runnable optimizedAckTask;
159    private long failoverRedeliveryWaitPeriod = 0;
160    private boolean transactedIndividualAck = false;
161    private boolean nonBlockingRedelivery = false;
162    private boolean consumerExpiryCheckEnabled = true;
163
164    /**
165     * Create a MessageConsumer
166     *
167     * @param session
168     * @param dest
169     * @param name
170     * @param selector
171     * @param prefetch
172     * @param maximumPendingMessageCount
173     * @param noLocal
174     * @param browser
175     * @param dispatchAsync
176     * @param messageListener
177     * @throws JMSException
178     */
179    public ActiveMQMessageConsumer(ActiveMQSession session, ConsumerId consumerId, ActiveMQDestination dest,
180            String name, String selector, int prefetch,
181            int maximumPendingMessageCount, boolean noLocal, boolean browser,
182            boolean dispatchAsync, MessageListener messageListener) throws JMSException {
183        if (dest == null) {
184            throw new InvalidDestinationException("Don't understand null destinations");
185        } else if (dest.getPhysicalName() == null) {
186            throw new InvalidDestinationException("The destination object was not given a physical name.");
187        } else if (dest.isTemporary()) {
188            String physicalName = dest.getPhysicalName();
189
190            if (physicalName == null) {
191                throw new IllegalArgumentException("Physical name of Destination should be valid: " + dest);
192            }
193
194            String connectionID = session.connection.getConnectionInfo().getConnectionId().getValue();
195
196            if (physicalName.indexOf(connectionID) < 0) {
197                throw new InvalidDestinationException("Cannot use a Temporary destination from another Connection");
198            }
199
200            if (session.connection.isDeleted(dest)) {
201                throw new InvalidDestinationException("Cannot use a Temporary destination that has been deleted");
202            }
203            if (prefetch < 0) {
204                throw new JMSException("Cannot have a prefetch size less than zero");
205            }
206        }
207        if (session.connection.isMessagePrioritySupported()) {
208            this.unconsumedMessages = new SimplePriorityMessageDispatchChannel();
209        }else {
210            this.unconsumedMessages = new FifoMessageDispatchChannel();
211        }
212
213        this.session = session;
214        this.redeliveryPolicy = session.connection.getRedeliveryPolicyMap().getEntryFor(dest);
215        if (this.redeliveryPolicy == null) {
216            this.redeliveryPolicy = new RedeliveryPolicy();
217        }
218        setTransformer(session.getTransformer());
219
220        this.info = new ConsumerInfo(consumerId);
221        this.info.setExclusive(this.session.connection.isExclusiveConsumer());
222        this.info.setClientId(this.session.connection.getClientID());
223        this.info.setSubscriptionName(name);
224        this.info.setPrefetchSize(prefetch);
225        this.info.setCurrentPrefetchSize(prefetch);
226        this.info.setMaximumPendingMessageLimit(maximumPendingMessageCount);
227        this.info.setNoLocal(noLocal);
228        this.info.setDispatchAsync(dispatchAsync);
229        this.info.setRetroactive(this.session.connection.isUseRetroactiveConsumer());
230        this.info.setSelector(null);
231
232        // Allows the options on the destination to configure the consumerInfo
233        if (dest.getOptions() != null) {
234            Map<String, Object> options = IntrospectionSupport.extractProperties(
235                new HashMap<String, Object>(dest.getOptions()), "consumer.");
236            IntrospectionSupport.setProperties(this.info, options);
237            if (options.size() > 0) {
238                String msg = "There are " + options.size()
239                    + " consumer options that couldn't be set on the consumer."
240                    + " Check the options are spelled correctly."
241                    + " Unknown parameters=[" + options + "]."
242                    + " This consumer cannot be started.";
243                LOG.warn(msg);
244                throw new ConfigurationException(msg);
245            }
246        }
247
248        this.info.setDestination(dest);
249        this.info.setBrowser(browser);
250        if (selector != null && selector.trim().length() != 0) {
251            // Validate the selector
252            SelectorParser.parse(selector);
253            this.info.setSelector(selector);
254            this.selector = selector;
255        } else if (info.getSelector() != null) {
256            // Validate the selector
257            SelectorParser.parse(this.info.getSelector());
258            this.selector = this.info.getSelector();
259        } else {
260            this.selector = null;
261        }
262
263        this.stats = new JMSConsumerStatsImpl(session.getSessionStats(), dest);
264        this.optimizeAcknowledge = session.connection.isOptimizeAcknowledge() && session.isAutoAcknowledge()
265                                   && !info.isBrowser();
266        if (this.optimizeAcknowledge) {
267            this.optimizeAcknowledgeTimeOut = session.connection.getOptimizeAcknowledgeTimeOut();
268            setOptimizedAckScheduledAckInterval(session.connection.getOptimizedAckScheduledAckInterval());
269        }
270
271        this.info.setOptimizedAcknowledge(this.optimizeAcknowledge);
272        this.failoverRedeliveryWaitPeriod = session.connection.getConsumerFailoverRedeliveryWaitPeriod();
273        this.nonBlockingRedelivery = session.connection.isNonBlockingRedelivery();
274        this.transactedIndividualAck = session.connection.isTransactedIndividualAck()
275                        || this.nonBlockingRedelivery
276                        || session.connection.isMessagePrioritySupported();
277        this.consumerExpiryCheckEnabled = session.connection.isConsumerExpiryCheckEnabled();
278        if (messageListener != null) {
279            setMessageListener(messageListener);
280        }
281        try {
282            this.session.addConsumer(this);
283            this.session.syncSendPacket(info);
284        } catch (JMSException e) {
285            this.session.removeConsumer(this);
286            throw e;
287        }
288
289        if (session.connection.isStarted()) {
290            start();
291        }
292    }
293
294    private boolean isAutoAcknowledgeEach() {
295        return session.isAutoAcknowledge() || ( session.isDupsOkAcknowledge() && getDestination().isQueue() );
296    }
297
298    private boolean isAutoAcknowledgeBatch() {
299        return session.isDupsOkAcknowledge() && !getDestination().isQueue() ;
300    }
301
302    @Override
303    public StatsImpl getStats() {
304        return stats;
305    }
306
307    public JMSConsumerStatsImpl getConsumerStats() {
308        return stats;
309    }
310
311    public RedeliveryPolicy getRedeliveryPolicy() {
312        return redeliveryPolicy;
313    }
314
315    /**
316     * Sets the redelivery policy used when messages are redelivered
317     */
318    public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) {
319        this.redeliveryPolicy = redeliveryPolicy;
320    }
321
322    public MessageTransformer getTransformer() {
323        return transformer;
324    }
325
326    /**
327     * Sets the transformer used to transform messages before they are sent on
328     * to the JMS bus
329     */
330    public void setTransformer(MessageTransformer transformer) {
331        this.transformer = transformer;
332    }
333
334    /**
335     * @return Returns the value.
336     */
337    public ConsumerId getConsumerId() {
338        return info.getConsumerId();
339    }
340
341    /**
342     * @return the consumer name - used for durable consumers
343     */
344    public String getConsumerName() {
345        return this.info.getSubscriptionName();
346    }
347
348    /**
349     * @return true if this consumer does not accept locally produced messages
350     */
351    protected boolean isNoLocal() {
352        return info.isNoLocal();
353    }
354
355    /**
356     * Retrieve is a browser
357     *
358     * @return true if a browser
359     */
360    protected boolean isBrowser() {
361        return info.isBrowser();
362    }
363
364    /**
365     * @return ActiveMQDestination
366     */
367    protected ActiveMQDestination getDestination() {
368        return info.getDestination();
369    }
370
371    /**
372     * @return Returns the prefetchNumber.
373     */
374    public int getPrefetchNumber() {
375        return info.getPrefetchSize();
376    }
377
378    /**
379     * @return true if this is a durable topic subscriber
380     */
381    public boolean isDurableSubscriber() {
382        return info.getSubscriptionName() != null && info.getDestination().isTopic();
383    }
384
385    /**
386     * Gets this message consumer's message selector expression.
387     *
388     * @return this message consumer's message selector, or null if no message
389     *         selector exists for the message consumer (that is, if the message
390     *         selector was not set or was set to null or the empty string)
391     * @throws JMSException if the JMS provider fails to receive the next
392     *                 message due to some internal error.
393     */
394    @Override
395    public String getMessageSelector() throws JMSException {
396        checkClosed();
397        return selector;
398    }
399
400    /**
401     * Gets the message consumer's <CODE>MessageListener</CODE>.
402     *
403     * @return the listener for the message consumer, or null if no listener is
404     *         set
405     * @throws JMSException if the JMS provider fails to get the message
406     *                 listener due to some internal error.
407     * @see javax.jms.MessageConsumer#setMessageListener(javax.jms.MessageListener)
408     */
409    @Override
410    public MessageListener getMessageListener() throws JMSException {
411        checkClosed();
412        return this.messageListener.get();
413    }
414
415    /**
416     * Sets the message consumer's <CODE>MessageListener</CODE>.
417     * <P>
418     * Setting the message listener to null is the equivalent of unsetting the
419     * message listener for the message consumer.
420     * <P>
421     * The effect of calling <CODE>MessageConsumer.setMessageListener</CODE>
422     * while messages are being consumed by an existing listener or the consumer
423     * is being used to consume messages synchronously is undefined.
424     *
425     * @param listener the listener to which the messages are to be delivered
426     * @throws JMSException if the JMS provider fails to receive the next
427     *                 message due to some internal error.
428     * @see javax.jms.MessageConsumer#getMessageListener
429     */
430    @Override
431    public void setMessageListener(MessageListener listener) throws JMSException {
432        checkClosed();
433        if (info.getPrefetchSize() == 0) {
434            throw new JMSException("Illegal prefetch size of zero. This setting is not supported for asynchronous consumers please set a value of at least 1");
435        }
436        if (listener != null) {
437            boolean wasRunning = session.isRunning();
438            if (wasRunning) {
439                session.stop();
440            }
441
442            this.messageListener.set(listener);
443            session.redispatch(this, unconsumedMessages);
444
445            if (wasRunning) {
446                session.start();
447            }
448        } else {
449            this.messageListener.set(null);
450        }
451    }
452
453    @Override
454    public MessageAvailableListener getAvailableListener() {
455        return availableListener;
456    }
457
458    /**
459     * Sets the listener used to notify synchronous consumers that there is a
460     * message available so that the {@link MessageConsumer#receiveNoWait()} can
461     * be called.
462     */
463    @Override
464    public void setAvailableListener(MessageAvailableListener availableListener) {
465        this.availableListener = availableListener;
466    }
467
468    /**
469     * Used to get an enqueued message from the unconsumedMessages list. The
470     * amount of time this method blocks is based on the timeout value. - if
471     * timeout==-1 then it blocks until a message is received. - if timeout==0
472     * then it it tries to not block at all, it returns a message if it is
473     * available - if timeout>0 then it blocks up to timeout amount of time.
474     * Expired messages will consumed by this method.
475     *
476     * @throws JMSException
477     * @return null if we timeout or if the consumer is closed.
478     */
479    private MessageDispatch dequeue(long timeout) throws JMSException {
480        try {
481            long deadline = 0;
482            if (timeout > 0) {
483                deadline = System.currentTimeMillis() + timeout;
484            }
485            while (true) {
486                MessageDispatch md = unconsumedMessages.dequeue(timeout);
487                if (md == null) {
488                    if (timeout > 0 && !unconsumedMessages.isClosed()) {
489                        timeout = Math.max(deadline - System.currentTimeMillis(), 0);
490                    } else {
491                        if (failureError != null) {
492                            throw JMSExceptionSupport.create(failureError);
493                        } else {
494                            return null;
495                        }
496                    }
497                } else if (md.getMessage() == null) {
498                    return null;
499                } else if (consumeExpiredMessage(md)) {
500                    LOG.debug("{} received expired message: {}", getConsumerId(), md);
501                    beforeMessageIsConsumed(md);
502                    afterMessageIsConsumed(md, true);
503                    if (timeout > 0) {
504                        timeout = Math.max(deadline - System.currentTimeMillis(), 0);
505                    }
506                    sendPullCommand(timeout);
507                } else if (redeliveryExceeded(md)) {
508                    LOG.debug("{} received with excessive redelivered: {}", getConsumerId(), md);
509                    posionAck(md, "dispatch to " + getConsumerId() + " exceeds redelivery policy limit:" + redeliveryPolicy);
510                    if (timeout > 0) {
511                        timeout = Math.max(deadline - System.currentTimeMillis(), 0);
512                    }
513                    sendPullCommand(timeout);
514                } else {
515                    if (LOG.isTraceEnabled()) {
516                        LOG.trace(getConsumerId() + " received message: " + md);
517                    }
518                    return md;
519                }
520            }
521        } catch (InterruptedException e) {
522            Thread.currentThread().interrupt();
523            throw JMSExceptionSupport.create(e);
524        }
525    }
526
527    private boolean consumeExpiredMessage(MessageDispatch dispatch) {
528        if (dispatch.getMessage().isExpired()) {
529            return !isBrowser() && isConsumerExpiryCheckEnabled();
530        }
531
532        return false;
533    }
534
535    private void posionAck(MessageDispatch md, String cause) throws JMSException {
536        MessageAck posionAck = new MessageAck(md, MessageAck.POSION_ACK_TYPE, 1);
537        posionAck.setFirstMessageId(md.getMessage().getMessageId());
538        posionAck.setPoisonCause(new Throwable(cause));
539        session.sendAck(posionAck);
540    }
541
542    private boolean redeliveryExceeded(MessageDispatch md) {
543        try {
544            return session.getTransacted()
545                    && redeliveryPolicy != null
546                    && redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES
547                    && md.getRedeliveryCounter() > redeliveryPolicy.getMaximumRedeliveries()
548                    // redeliveryCounter > x expected after resend via brokerRedeliveryPlugin
549                    && md.getMessage().getProperty("redeliveryDelay") == null;
550        } catch (Exception ignored) {
551            return false;
552        }
553    }
554
555    /**
556     * Receives the next message produced for this message consumer.
557     * <P>
558     * This call blocks indefinitely until a message is produced or until this
559     * message consumer is closed.
560     * <P>
561     * If this <CODE>receive</CODE> is done within a transaction, the consumer
562     * retains the message until the transaction commits.
563     *
564     * @return the next message produced for this message consumer, or null if
565     *         this message consumer is concurrently closed
566     */
567    @Override
568    public Message receive() throws JMSException {
569        checkClosed();
570        checkMessageListener();
571
572        sendPullCommand(0);
573        MessageDispatch md = dequeue(-1);
574        if (md == null) {
575            return null;
576        }
577
578        beforeMessageIsConsumed(md);
579        afterMessageIsConsumed(md, false);
580
581        return createActiveMQMessage(md);
582    }
583
584    /**
585     * @param md
586     *      the MessageDispatch that arrived from the Broker.
587     *
588     * @return an ActiveMQMessage initialized from the Message in the dispatch.
589     */
590    private ActiveMQMessage createActiveMQMessage(final MessageDispatch md) throws JMSException {
591        ActiveMQMessage m = (ActiveMQMessage)md.getMessage().copy();
592        if (m.getDataStructureType()==CommandTypes.ACTIVEMQ_BLOB_MESSAGE) {
593            ((ActiveMQBlobMessage)m).setBlobDownloader(new BlobDownloader(session.getBlobTransferPolicy()));
594        }
595        if (m.getDataStructureType() == CommandTypes.ACTIVEMQ_OBJECT_MESSAGE) {
596            ((ActiveMQObjectMessage)m).setTrustAllPackages(session.getConnection().isTrustAllPackages());
597            ((ActiveMQObjectMessage)m).setTrustedPackages(session.getConnection().getTrustedPackages());
598        }
599        if (transformer != null) {
600            Message transformedMessage = transformer.consumerTransform(session, this, m);
601            if (transformedMessage != null) {
602                m = ActiveMQMessageTransformation.transformMessage(transformedMessage, session.connection);
603            }
604        }
605        if (session.isClientAcknowledge()) {
606            m.setAcknowledgeCallback(new Callback() {
607                @Override
608                public void execute() throws Exception {
609                    session.checkClosed();
610                    session.acknowledge();
611                }
612            });
613        } else if (session.isIndividualAcknowledge()) {
614            m.setAcknowledgeCallback(new Callback() {
615                @Override
616                public void execute() throws Exception {
617                    session.checkClosed();
618                    acknowledge(md);
619                }
620            });
621        }
622        return m;
623    }
624
625    /**
626     * Receives the next message that arrives within the specified timeout
627     * interval.
628     * <P>
629     * This call blocks until a message arrives, the timeout expires, or this
630     * message consumer is closed. A <CODE>timeout</CODE> of zero never
631     * expires, and the call blocks indefinitely.
632     *
633     * @param timeout the timeout value (in milliseconds), a time out of zero
634     *                never expires.
635     * @return the next message produced for this message consumer, or null if
636     *         the timeout expires or this message consumer is concurrently
637     *         closed
638     */
639    @Override
640    public Message receive(long timeout) throws JMSException {
641        checkClosed();
642        checkMessageListener();
643        if (timeout == 0) {
644            return this.receive();
645        }
646
647        sendPullCommand(timeout);
648        while (timeout > 0) {
649
650            MessageDispatch md;
651            if (info.getPrefetchSize() == 0) {
652                md = dequeue(-1); // We let the broker let us know when we timeout.
653            } else {
654                md = dequeue(timeout);
655            }
656
657            if (md == null) {
658                return null;
659            }
660
661            beforeMessageIsConsumed(md);
662            afterMessageIsConsumed(md, false);
663            return createActiveMQMessage(md);
664        }
665        return null;
666    }
667
668    /**
669     * Receives the next message if one is immediately available.
670     *
671     * @return the next message produced for this message consumer, or null if
672     *         one is not available
673     * @throws JMSException if the JMS provider fails to receive the next
674     *                 message due to some internal error.
675     */
676    @Override
677    public Message receiveNoWait() throws JMSException {
678        checkClosed();
679        checkMessageListener();
680        sendPullCommand(-1);
681
682        MessageDispatch md;
683        if (info.getPrefetchSize() == 0) {
684            md = dequeue(-1); // We let the broker let us know when we
685            // timeout.
686        } else {
687            md = dequeue(0);
688        }
689
690        if (md == null) {
691            return null;
692        }
693
694        beforeMessageIsConsumed(md);
695        afterMessageIsConsumed(md, false);
696        return createActiveMQMessage(md);
697    }
698
699    /**
700     * Closes the message consumer.
701     * <P>
702     * Since a provider may allocate some resources on behalf of a <CODE>
703     * MessageConsumer</CODE>
704     * outside the Java virtual machine, clients should close them when they are
705     * not needed. Relying on garbage collection to eventually reclaim these
706     * resources may not be timely enough.
707     * <P>
708     * This call blocks until a <CODE>receive</CODE> or message listener in
709     * progress has completed. A blocked message consumer <CODE>receive </CODE>
710     * call returns null when this message consumer is closed.
711     *
712     * @throws JMSException if the JMS provider fails to close the consumer due
713     *                 to some internal error.
714     */
715    @Override
716    public void close() throws JMSException {
717        if (!unconsumedMessages.isClosed()) {
718            if (!deliveredMessages.isEmpty() && session.getTransactionContext().isInTransaction()) {
719                session.getTransactionContext().addSynchronization(new Synchronization() {
720                    @Override
721                    public void afterCommit() throws Exception {
722                        doClose();
723                    }
724
725                    @Override
726                    public void afterRollback() throws Exception {
727                        doClose();
728                    }
729                });
730            } else {
731                doClose();
732            }
733        }
734    }
735
736    void doClose() throws JMSException {
737        dispose();
738        RemoveInfo removeCommand = info.createRemoveCommand();
739        LOG.debug("remove: {}, lastDeliveredSequenceId: {}", getConsumerId(), lastDeliveredSequenceId);
740        removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId);
741        this.session.asyncSendPacket(removeCommand);
742    }
743
744    void inProgressClearRequired() {
745        inProgressClearRequiredFlag.incrementAndGet();
746        // deal with delivered messages async to avoid lock contention with in progress acks
747        clearDeliveredList = true;
748        // force a rollback if we will be acking in a transaction after/during failover
749        // bc acks are async they may not get there reliably on reconnect and the consumer
750        // may not be aware of the reconnect in a timely fashion if in onMessage
751        if (!deliveredMessages.isEmpty() && session.getTransactionContext().isInTransaction()) {
752            session.getTransactionContext().setRollbackOnly(true);
753        }
754    }
755
756    void clearMessagesInProgress() {
757        if (inProgressClearRequiredFlag.get() > 0) {
758            synchronized (unconsumedMessages.getMutex()) {
759                if (inProgressClearRequiredFlag.get() > 0) {
760                    LOG.debug("{} clearing unconsumed list ({}) on transport interrupt", getConsumerId(), unconsumedMessages.size());
761                    // ensure unconsumed are rolledback up front as they may get redelivered to another consumer
762                    List<MessageDispatch> list = unconsumedMessages.removeAll();
763                    if (!this.info.isBrowser()) {
764                        for (MessageDispatch old : list) {
765                            session.connection.rollbackDuplicate(this, old.getMessage());
766                        }
767                    }
768                    // allow dispatch on this connection to resume
769                    session.connection.transportInterruptionProcessingComplete();
770                    inProgressClearRequiredFlag.decrementAndGet();
771
772                    // Wake up any blockers and allow them to recheck state.
773                    unconsumedMessages.getMutex().notifyAll();
774                }
775            }
776        }
777        clearDeliveredList();
778    }
779
780    void deliverAcks() {
781        MessageAck ack = null;
782        if (deliveryingAcknowledgements.compareAndSet(false, true)) {
783            synchronized(deliveredMessages) {
784                if (isAutoAcknowledgeEach()) {
785                    ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
786                    if (ack != null) {
787                        deliveredMessages.clear();
788                        ackCounter = 0;
789                    } else {
790                        ack = pendingAck;
791                        pendingAck = null;
792                    }
793                } else if (pendingAck != null && pendingAck.isStandardAck()) {
794                    ack = pendingAck;
795                    pendingAck = null;
796                }
797            }
798            if (ack != null) {
799                final MessageAck ackToSend = ack;
800
801                if (executorService == null) {
802                    executorService = Executors.newSingleThreadExecutor();
803                }
804                executorService.submit(new Runnable() {
805                    @Override
806                    public void run() {
807                        try {
808                            session.sendAck(ackToSend,true);
809                        } catch (JMSException e) {
810                            LOG.error(getConsumerId() + " failed to delivered acknowledgements", e);
811                        } finally {
812                            deliveryingAcknowledgements.set(false);
813                        }
814                    }
815                });
816            } else {
817                deliveryingAcknowledgements.set(false);
818            }
819        }
820    }
821
822    public void dispose() throws JMSException {
823        if (!unconsumedMessages.isClosed()) {
824
825            // Do we have any acks we need to send out before closing?
826            // Ack any delivered messages now.
827            if (!session.getTransacted()) {
828                deliverAcks();
829                if (isAutoAcknowledgeBatch()) {
830                    acknowledge();
831                }
832            }
833            if (executorService != null) {
834                ThreadPoolUtils.shutdownGraceful(executorService, 60000L);
835                executorService = null;
836            }
837            if (optimizedAckTask != null) {
838                this.session.connection.getScheduler().cancel(optimizedAckTask);
839                optimizedAckTask = null;
840            }
841
842            if (session.isClientAcknowledge() || session.isIndividualAcknowledge()) {
843                if (!this.info.isBrowser()) {
844                    // rollback duplicates that aren't acknowledged
845                    List<MessageDispatch> tmp = null;
846                    synchronized (this.deliveredMessages) {
847                        tmp = new ArrayList<MessageDispatch>(this.deliveredMessages);
848                    }
849                    for (MessageDispatch old : tmp) {
850                        this.session.connection.rollbackDuplicate(this, old.getMessage());
851                    }
852                    tmp.clear();
853                }
854            }
855            if (!session.isTransacted()) {
856                synchronized(deliveredMessages) {
857                    deliveredMessages.clear();
858                }
859            }
860            unconsumedMessages.close();
861            this.session.removeConsumer(this);
862            List<MessageDispatch> list = unconsumedMessages.removeAll();
863            if (!this.info.isBrowser()) {
864                for (MessageDispatch old : list) {
865                    // ensure we don't filter this as a duplicate
866                    if (old.getMessage() != null) {
867                        LOG.debug("on close, rollback duplicate: {}", old.getMessage().getMessageId());
868                    }
869                    session.connection.rollbackDuplicate(this, old.getMessage());
870                }
871            }
872        }
873    }
874
875    /**
876     * @throws IllegalStateException
877     */
878    protected void checkClosed() throws IllegalStateException {
879        if (unconsumedMessages.isClosed()) {
880            throw new IllegalStateException("The Consumer is closed");
881        }
882    }
883
884    /**
885     * If we have a zero prefetch specified then send a pull command to the
886     * broker to pull a message we are about to receive
887     */
888    protected void sendPullCommand(long timeout) throws JMSException {
889        clearDeliveredList();
890        if (info.getCurrentPrefetchSize() == 0 && unconsumedMessages.isEmpty()) {
891            MessagePull messagePull = new MessagePull();
892            messagePull.configure(info);
893            messagePull.setTimeout(timeout);
894            session.asyncSendPacket(messagePull);
895        }
896    }
897
898    protected void checkMessageListener() throws JMSException {
899        session.checkMessageListener();
900    }
901
902    protected void setOptimizeAcknowledge(boolean value) {
903        if (optimizeAcknowledge && !value) {
904            deliverAcks();
905        }
906        optimizeAcknowledge = value;
907    }
908
909    protected void setPrefetchSize(int prefetch) {
910        deliverAcks();
911        this.info.setCurrentPrefetchSize(prefetch);
912    }
913
914    private void beforeMessageIsConsumed(MessageDispatch md) throws JMSException {
915        md.setDeliverySequenceId(session.getNextDeliveryId());
916        lastDeliveredSequenceId = md.getMessage().getMessageId().getBrokerSequenceId();
917        if (!isAutoAcknowledgeBatch()) {
918            synchronized(deliveredMessages) {
919                deliveredMessages.addFirst(md);
920            }
921            if (session.getTransacted()) {
922                if (transactedIndividualAck) {
923                    immediateIndividualTransactedAck(md);
924                } else {
925                    ackLater(md, MessageAck.DELIVERED_ACK_TYPE);
926                }
927            }
928        }
929    }
930
931    private void immediateIndividualTransactedAck(MessageDispatch md) throws JMSException {
932        // acks accumulate on the broker pending transaction completion to indicate
933        // delivery status
934        registerSync();
935        MessageAck ack = new MessageAck(md, MessageAck.INDIVIDUAL_ACK_TYPE, 1);
936        ack.setTransactionId(session.getTransactionContext().getTransactionId());
937        session.sendAck(ack);
938    }
939
940    private void afterMessageIsConsumed(MessageDispatch md, boolean messageExpired) throws JMSException {
941        if (unconsumedMessages.isClosed()) {
942            return;
943        }
944        if (messageExpired) {
945            acknowledge(md, MessageAck.EXPIRED_ACK_TYPE);
946            stats.getExpiredMessageCount().increment();
947        } else {
948            stats.onMessage();
949            if (session.getTransacted()) {
950                // Do nothing.
951            } else if (isAutoAcknowledgeEach()) {
952                if (deliveryingAcknowledgements.compareAndSet(false, true)) {
953                    synchronized (deliveredMessages) {
954                        if (!deliveredMessages.isEmpty()) {
955                            if (optimizeAcknowledge) {
956                                ackCounter++;
957
958                                // AMQ-3956 evaluate both expired and normal msgs as
959                                // otherwise consumer may get stalled
960                                if (ackCounter + deliveredCounter >= (info.getPrefetchSize() * .65) || (optimizeAcknowledgeTimeOut > 0 && System.currentTimeMillis() >= (optimizeAckTimestamp + optimizeAcknowledgeTimeOut))) {
961                                    MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
962                                    if (ack != null) {
963                                        deliveredMessages.clear();
964                                        ackCounter = 0;
965                                        session.sendAck(ack);
966                                        optimizeAckTimestamp = System.currentTimeMillis();
967                                    }
968                                    // AMQ-3956 - as further optimization send
969                                    // ack for expired msgs when there are any.
970                                    // This resets the deliveredCounter to 0 so that
971                                    // we won't sent standard acks with every msg just
972                                    // because the deliveredCounter just below
973                                    // 0.5 * prefetch as used in ackLater()
974                                    if (pendingAck != null && deliveredCounter > 0) {
975                                        session.sendAck(pendingAck);
976                                        pendingAck = null;
977                                        deliveredCounter = 0;
978                                    }
979                                }
980                            } else {
981                                MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
982                                if (ack!=null) {
983                                    deliveredMessages.clear();
984                                    session.sendAck(ack);
985                                }
986                            }
987                        }
988                    }
989                    deliveryingAcknowledgements.set(false);
990                }
991            } else if (isAutoAcknowledgeBatch()) {
992                ackLater(md, MessageAck.STANDARD_ACK_TYPE);
993            } else if (session.isClientAcknowledge()||session.isIndividualAcknowledge()) {
994                boolean messageUnackedByConsumer = false;
995                synchronized (deliveredMessages) {
996                    messageUnackedByConsumer = deliveredMessages.contains(md);
997                }
998                if (messageUnackedByConsumer) {
999                    ackLater(md, MessageAck.DELIVERED_ACK_TYPE);
1000                }
1001            }
1002            else {
1003                throw new IllegalStateException("Invalid session state.");
1004            }
1005        }
1006    }
1007
1008    /**
1009     * Creates a MessageAck for all messages contained in deliveredMessages.
1010     * Caller should hold the lock for deliveredMessages.
1011     *
1012     * @param type Ack-Type (i.e. MessageAck.STANDARD_ACK_TYPE)
1013     * @return <code>null</code> if nothing to ack.
1014     */
1015    private MessageAck makeAckForAllDeliveredMessages(byte type) {
1016        synchronized (deliveredMessages) {
1017            if (deliveredMessages.isEmpty()) {
1018                return null;
1019            }
1020
1021            MessageDispatch md = deliveredMessages.getFirst();
1022            MessageAck ack = new MessageAck(md, type, deliveredMessages.size());
1023            ack.setFirstMessageId(deliveredMessages.getLast().getMessage().getMessageId());
1024            return ack;
1025        }
1026    }
1027
1028    private void ackLater(MessageDispatch md, byte ackType) throws JMSException {
1029
1030        // Don't acknowledge now, but we may need to let the broker know the
1031        // consumer got the message to expand the pre-fetch window
1032        if (session.getTransacted()) {
1033            registerSync();
1034        }
1035
1036        deliveredCounter++;
1037
1038        synchronized(deliveredMessages) {
1039            MessageAck oldPendingAck = pendingAck;
1040            pendingAck = new MessageAck(md, ackType, deliveredCounter);
1041            pendingAck.setTransactionId(session.getTransactionContext().getTransactionId());
1042            if( oldPendingAck==null ) {
1043                pendingAck.setFirstMessageId(pendingAck.getLastMessageId());
1044            } else if ( oldPendingAck.getAckType() == pendingAck.getAckType() ) {
1045                pendingAck.setFirstMessageId(oldPendingAck.getFirstMessageId());
1046            } else {
1047                // old pending ack being superseded by ack of another type, if is is not a delivered
1048                // ack and hence important, send it now so it is not lost.
1049                if (!oldPendingAck.isDeliveredAck()) {
1050                    LOG.debug("Sending old pending ack {}, new pending: {}", oldPendingAck, pendingAck);
1051                    session.sendAck(oldPendingAck);
1052                } else {
1053                    LOG.debug("dropping old pending ack {}, new pending: {}", oldPendingAck, pendingAck);
1054                }
1055            }
1056            // AMQ-3956 evaluate both expired and normal msgs as
1057            // otherwise consumer may get stalled
1058            if ((0.5 * info.getPrefetchSize()) <= (deliveredCounter + ackCounter - additionalWindowSize)) {
1059                LOG.debug("ackLater: sending: {}", pendingAck);
1060                session.sendAck(pendingAck);
1061                pendingAck=null;
1062                deliveredCounter = 0;
1063                additionalWindowSize = 0;
1064            }
1065        }
1066    }
1067
1068    private void registerSync() throws JMSException {
1069        session.doStartTransaction();
1070        if (!synchronizationRegistered) {
1071            synchronizationRegistered = true;
1072            session.getTransactionContext().addSynchronization(new Synchronization() {
1073                @Override
1074                public void beforeEnd() throws Exception {
1075                    if (transactedIndividualAck) {
1076                        clearDeliveredList();
1077                        waitForRedeliveries();
1078                        synchronized(deliveredMessages) {
1079                            rollbackOnFailedRecoveryRedelivery();
1080                        }
1081                    } else {
1082                        acknowledge();
1083                    }
1084                    synchronizationRegistered = false;
1085                }
1086
1087                @Override
1088                public void afterCommit() throws Exception {
1089                    commit();
1090                    synchronizationRegistered = false;
1091                }
1092
1093                @Override
1094                public void afterRollback() throws Exception {
1095                    rollback();
1096                    synchronizationRegistered = false;
1097                }
1098            });
1099        }
1100    }
1101
1102    /**
1103     * Acknowledge all the messages that have been delivered to the client up to
1104     * this point.
1105     *
1106     * @throws JMSException
1107     */
1108    public void acknowledge() throws JMSException {
1109        clearDeliveredList();
1110        waitForRedeliveries();
1111        synchronized(deliveredMessages) {
1112            // Acknowledge all messages so far.
1113            MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
1114            if (ack == null) {
1115                return; // no msgs
1116            }
1117
1118            if (session.getTransacted()) {
1119                rollbackOnFailedRecoveryRedelivery();
1120                session.doStartTransaction();
1121                ack.setTransactionId(session.getTransactionContext().getTransactionId());
1122            }
1123
1124            pendingAck = null;
1125            session.sendAck(ack);
1126
1127            // Adjust the counters
1128            deliveredCounter = Math.max(0, deliveredCounter - deliveredMessages.size());
1129            additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size());
1130
1131            if (!session.getTransacted()) {
1132                deliveredMessages.clear();
1133            }
1134        }
1135    }
1136
1137    private void waitForRedeliveries() {
1138        if (failoverRedeliveryWaitPeriod > 0 && previouslyDeliveredMessages != null) {
1139            long expiry = System.currentTimeMillis() + failoverRedeliveryWaitPeriod;
1140            int numberNotReplayed;
1141            do {
1142                numberNotReplayed = 0;
1143                synchronized(deliveredMessages) {
1144                    if (previouslyDeliveredMessages != null) {
1145                        for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
1146                            if (!entry.getValue()) {
1147                                numberNotReplayed++;
1148                            }
1149                        }
1150                    }
1151                }
1152                if (numberNotReplayed > 0) {
1153                    LOG.info("waiting for redelivery of {} in transaction: {}, to consumer: {}",
1154                             numberNotReplayed, this.getConsumerId(), previouslyDeliveredMessages.transactionId);
1155                    try {
1156                        Thread.sleep(Math.max(500, failoverRedeliveryWaitPeriod/4));
1157                    } catch (InterruptedException outOfhere) {
1158                        break;
1159                    }
1160                }
1161            } while (numberNotReplayed > 0 && expiry < System.currentTimeMillis());
1162        }
1163    }
1164
1165    /*
1166     * called with deliveredMessages locked
1167     */
1168    private void rollbackOnFailedRecoveryRedelivery() throws JMSException {
1169        if (previouslyDeliveredMessages != null) {
1170            // if any previously delivered messages was not re-delivered, transaction is invalid and must rollback
1171            // as messages have been dispatched else where.
1172            int numberNotReplayed = 0;
1173            for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
1174                if (!entry.getValue()) {
1175                    numberNotReplayed++;
1176                    LOG.debug("previously delivered message has not been replayed in transaction: {}, messageId: {}",
1177                              previouslyDeliveredMessages.transactionId, entry.getKey());
1178                }
1179            }
1180            if (numberNotReplayed > 0) {
1181                String message = "rolling back transaction ("
1182                    + previouslyDeliveredMessages.transactionId + ") post failover recovery. " + numberNotReplayed
1183                    + " previously delivered message(s) not replayed to consumer: " + this.getConsumerId();
1184                LOG.warn(message);
1185                throw new TransactionRolledBackException(message);
1186            }
1187        }
1188    }
1189
1190    void acknowledge(MessageDispatch md) throws JMSException {
1191        acknowledge(md, MessageAck.INDIVIDUAL_ACK_TYPE);
1192    }
1193
1194    void acknowledge(MessageDispatch md, byte ackType) throws JMSException {
1195        MessageAck ack = new MessageAck(md, ackType, 1);
1196        if (ack.isExpiredAck()) {
1197            ack.setFirstMessageId(ack.getLastMessageId());
1198        }
1199        session.sendAck(ack);
1200        synchronized(deliveredMessages){
1201            deliveredMessages.remove(md);
1202        }
1203    }
1204
1205    public void commit() throws JMSException {
1206        synchronized (deliveredMessages) {
1207            deliveredMessages.clear();
1208            clearPreviouslyDelivered();
1209        }
1210        redeliveryDelay = 0;
1211    }
1212
1213    public void rollback() throws JMSException {
1214        clearDeliveredList();
1215        synchronized (unconsumedMessages.getMutex()) {
1216            if (optimizeAcknowledge) {
1217                // remove messages read but not acked at the broker yet through
1218                // optimizeAcknowledge
1219                if (!this.info.isBrowser()) {
1220                    synchronized(deliveredMessages) {
1221                        for (int i = 0; (i < deliveredMessages.size()) && (i < ackCounter); i++) {
1222                            // ensure we don't filter this as a duplicate
1223                            MessageDispatch md = deliveredMessages.removeLast();
1224                            session.connection.rollbackDuplicate(this, md.getMessage());
1225                        }
1226                    }
1227                }
1228            }
1229            synchronized(deliveredMessages) {
1230                rollbackPreviouslyDeliveredAndNotRedelivered();
1231                if (deliveredMessages.isEmpty()) {
1232                    return;
1233                }
1234
1235                // use initial delay for first redelivery
1236                MessageDispatch lastMd = deliveredMessages.getFirst();
1237                final int currentRedeliveryCount = lastMd.getMessage().getRedeliveryCounter();
1238                if (currentRedeliveryCount > 0) {
1239                    redeliveryDelay = redeliveryPolicy.getNextRedeliveryDelay(redeliveryDelay);
1240                } else {
1241                    redeliveryDelay = redeliveryPolicy.getInitialRedeliveryDelay();
1242                }
1243                MessageId firstMsgId = deliveredMessages.getLast().getMessage().getMessageId();
1244
1245                for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) {
1246                    MessageDispatch md = iter.next();
1247                    md.getMessage().onMessageRolledBack();
1248                    // ensure we don't filter this as a duplicate
1249                    session.connection.rollbackDuplicate(this, md.getMessage());
1250                }
1251
1252                if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES
1253                    && lastMd.getMessage().getRedeliveryCounter() > redeliveryPolicy.getMaximumRedeliveries()) {
1254                    // We need to NACK the messages so that they get sent to the
1255                    // DLQ.
1256                    // Acknowledge the last message.
1257
1258                    MessageAck ack = new MessageAck(lastMd, MessageAck.POSION_ACK_TYPE, deliveredMessages.size());
1259                    ack.setFirstMessageId(firstMsgId);
1260                    ack.setPoisonCause(new Throwable("Exceeded redelivery policy limit:" + redeliveryPolicy
1261                            + ", cause:" + lastMd.getRollbackCause(), lastMd.getRollbackCause()));
1262                    session.sendAck(ack,true);
1263                    // Adjust the window size.
1264                    additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size());
1265                    redeliveryDelay = 0;
1266
1267                    deliveredCounter -= deliveredMessages.size();
1268                    deliveredMessages.clear();
1269
1270                } else {
1271
1272                    // only redelivery_ack after first delivery
1273                    if (currentRedeliveryCount > 0) {
1274                        MessageAck ack = new MessageAck(lastMd, MessageAck.REDELIVERED_ACK_TYPE, deliveredMessages.size());
1275                        ack.setFirstMessageId(firstMsgId);
1276                        session.sendAck(ack,true);
1277                    }
1278
1279                    // stop the delivery of messages.
1280                    if (nonBlockingRedelivery) {
1281                        if (!unconsumedMessages.isClosed()) {
1282
1283                            final LinkedList<MessageDispatch> pendingRedeliveries =
1284                                new LinkedList<MessageDispatch>(deliveredMessages);
1285
1286                            Collections.reverse(pendingRedeliveries);
1287
1288                            deliveredCounter -= deliveredMessages.size();
1289                            deliveredMessages.clear();
1290
1291                            // Start up the delivery again a little later.
1292                            session.getScheduler().executeAfterDelay(new Runnable() {
1293                                @Override
1294                                public void run() {
1295                                    try {
1296                                        if (!unconsumedMessages.isClosed()) {
1297                                            for(MessageDispatch dispatch : pendingRedeliveries) {
1298                                                session.dispatch(dispatch);
1299                                            }
1300                                        }
1301                                    } catch (Exception e) {
1302                                        session.connection.onAsyncException(e);
1303                                    }
1304                                }
1305                            }, redeliveryDelay);
1306                        }
1307
1308                    } else {
1309                        unconsumedMessages.stop();
1310
1311                        for (MessageDispatch md : deliveredMessages) {
1312                            unconsumedMessages.enqueueFirst(md);
1313                        }
1314
1315                        deliveredCounter -= deliveredMessages.size();
1316                        deliveredMessages.clear();
1317
1318                        if (redeliveryDelay > 0 && !unconsumedMessages.isClosed()) {
1319                            // Start up the delivery again a little later.
1320                            session.getScheduler().executeAfterDelay(new Runnable() {
1321                                @Override
1322                                public void run() {
1323                                    try {
1324                                        if (started.get()) {
1325                                            start();
1326                                        }
1327                                    } catch (JMSException e) {
1328                                        session.connection.onAsyncException(e);
1329                                    }
1330                                }
1331                            }, redeliveryDelay);
1332                        } else {
1333                            start();
1334                        }
1335                    }
1336                }
1337            }
1338        }
1339        if (messageListener.get() != null) {
1340            session.redispatch(this, unconsumedMessages);
1341        }
1342    }
1343
1344    /*
1345     * called with unconsumedMessages && deliveredMessages locked
1346     * remove any message not re-delivered as they can't be replayed to this
1347     * consumer on rollback
1348     */
1349    private void rollbackPreviouslyDeliveredAndNotRedelivered() {
1350        if (previouslyDeliveredMessages != null) {
1351            for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
1352                if (!entry.getValue()) {
1353                    LOG.trace("rollback non redelivered: {}" + entry.getKey());
1354                    removeFromDeliveredMessages(entry.getKey());
1355                }
1356            }
1357            clearPreviouslyDelivered();
1358        }
1359    }
1360
1361    /*
1362     * called with deliveredMessages locked
1363     */
1364    private void removeFromDeliveredMessages(MessageId key) {
1365        Iterator<MessageDispatch> iterator = deliveredMessages.iterator();
1366        while (iterator.hasNext()) {
1367            MessageDispatch candidate = iterator.next();
1368            if (key.equals(candidate.getMessage().getMessageId())) {
1369                session.connection.rollbackDuplicate(this, candidate.getMessage());
1370                iterator.remove();
1371                break;
1372            }
1373        }
1374    }
1375
1376    /*
1377     * called with deliveredMessages locked
1378     */
1379    private void clearPreviouslyDelivered() {
1380        if (previouslyDeliveredMessages != null) {
1381            previouslyDeliveredMessages.clear();
1382            previouslyDeliveredMessages = null;
1383        }
1384    }
1385
1386    @Override
1387    public void dispatch(MessageDispatch md) {
1388        MessageListener listener = this.messageListener.get();
1389        try {
1390            clearMessagesInProgress();
1391            clearDeliveredList();
1392            synchronized (unconsumedMessages.getMutex()) {
1393                if (!unconsumedMessages.isClosed()) {
1394                    if (this.info.isBrowser() || !session.connection.isDuplicate(this, md.getMessage())) {
1395                        if (listener != null && unconsumedMessages.isRunning()) {
1396                            if (redeliveryExceeded(md)) {
1397                                posionAck(md, "dispatch to " + getConsumerId() + " exceeds redelivery policy limit:" + redeliveryPolicy);
1398                                return;
1399                            }
1400                            ActiveMQMessage message = createActiveMQMessage(md);
1401                            beforeMessageIsConsumed(md);
1402                            try {
1403                                boolean expired = isConsumerExpiryCheckEnabled() && message.isExpired();
1404                                if (!expired) {
1405                                    listener.onMessage(message);
1406                                }
1407                                afterMessageIsConsumed(md, expired);
1408                            } catch (RuntimeException e) {
1409                                LOG.error("{} Exception while processing message: {}", getConsumerId(), md.getMessage().getMessageId(), e);
1410                                md.setRollbackCause(e);
1411                                if (isAutoAcknowledgeBatch() || isAutoAcknowledgeEach() || session.isIndividualAcknowledge()) {
1412                                    // schedual redelivery and possible dlq processing
1413                                    rollback();
1414                                } else {
1415                                    // Transacted or Client ack: Deliver the next message.
1416                                    afterMessageIsConsumed(md, false);
1417                                }
1418                            }
1419                        } else {
1420                            if (!unconsumedMessages.isRunning()) {
1421                                // delayed redelivery, ensure it can be re delivered
1422                                session.connection.rollbackDuplicate(this, md.getMessage());
1423                            }
1424                            unconsumedMessages.enqueue(md);
1425                            if (availableListener != null) {
1426                                availableListener.onMessageAvailable(this);
1427                            }
1428                        }
1429                    } else {
1430                        // deal with duplicate delivery
1431                        ConsumerId consumerWithPendingTransaction;
1432                        if (redeliveryExpectedInCurrentTransaction(md, true)) {
1433                            LOG.debug("{} tracking transacted redelivery {}", getConsumerId(), md.getMessage());
1434                            if (transactedIndividualAck) {
1435                                immediateIndividualTransactedAck(md);
1436                            } else {
1437                                session.sendAck(new MessageAck(md, MessageAck.DELIVERED_ACK_TYPE, 1));
1438                            }
1439                        } else if ((consumerWithPendingTransaction = redeliveryPendingInCompetingTransaction(md)) != null) {
1440                            LOG.warn("{} delivering duplicate {}, pending transaction completion on {} will rollback", getConsumerId(), md.getMessage(), consumerWithPendingTransaction);
1441                            session.getConnection().rollbackDuplicate(this, md.getMessage());
1442                            dispatch(md);
1443                        } else {
1444                            LOG.warn("{} suppressing duplicate delivery on connection, poison acking: {}", getConsumerId(), md);
1445                            posionAck(md, "Suppressing duplicate delivery on connection, consumer " + getConsumerId());
1446                        }
1447                    }
1448                }
1449            }
1450            if (++dispatchedCount % 1000 == 0) {
1451                dispatchedCount = 0;
1452                Thread.yield();
1453            }
1454        } catch (Exception e) {
1455            session.connection.onClientInternalException(e);
1456        }
1457    }
1458
1459    private boolean redeliveryExpectedInCurrentTransaction(MessageDispatch md, boolean markReceipt) {
1460        if (session.isTransacted()) {
1461            synchronized (deliveredMessages) {
1462                if (previouslyDeliveredMessages != null) {
1463                    if (previouslyDeliveredMessages.containsKey(md.getMessage().getMessageId())) {
1464                        if (markReceipt) {
1465                            previouslyDeliveredMessages.put(md.getMessage().getMessageId(), true);
1466                        }
1467                        return true;
1468                    }
1469                }
1470            }
1471        }
1472        return false;
1473    }
1474
1475    private ConsumerId redeliveryPendingInCompetingTransaction(MessageDispatch md) {
1476        for (ActiveMQSession activeMQSession: session.connection.getSessions()) {
1477            for (ActiveMQMessageConsumer activeMQMessageConsumer : activeMQSession.consumers) {
1478                if (activeMQMessageConsumer.redeliveryExpectedInCurrentTransaction(md, false)) {
1479                    return activeMQMessageConsumer.getConsumerId();
1480                }
1481            }
1482        }
1483        return null;
1484    }
1485
1486    // async (on next call) clear or track delivered as they may be flagged as duplicates if they arrive again
1487    private void clearDeliveredList() {
1488        if (clearDeliveredList) {
1489            synchronized (deliveredMessages) {
1490                if (clearDeliveredList) {
1491                    if (!deliveredMessages.isEmpty()) {
1492                        if (session.isTransacted()) {
1493
1494                            if (previouslyDeliveredMessages == null) {
1495                                previouslyDeliveredMessages = new PreviouslyDeliveredMap<MessageId, Boolean>(session.getTransactionContext().getTransactionId());
1496                            }
1497                            for (MessageDispatch delivered : deliveredMessages) {
1498                                previouslyDeliveredMessages.put(delivered.getMessage().getMessageId(), false);
1499                            }
1500                            LOG.debug("{} tracking existing transacted {} delivered list ({}) on transport interrupt",
1501                                      getConsumerId(), previouslyDeliveredMessages.transactionId, deliveredMessages.size());
1502                        } else {
1503                            if (session.isClientAcknowledge()) {
1504                                LOG.debug("{} rolling back delivered list ({}) on transport interrupt", getConsumerId(), deliveredMessages.size());
1505                                // allow redelivery
1506                                if (!this.info.isBrowser()) {
1507                                    for (MessageDispatch md: deliveredMessages) {
1508                                        this.session.connection.rollbackDuplicate(this, md.getMessage());
1509                                    }
1510                                }
1511                            }
1512                            LOG.debug("{} clearing delivered list ({}) on transport interrupt", getConsumerId(), deliveredMessages.size());
1513                            deliveredMessages.clear();
1514                            pendingAck = null;
1515                        }
1516                    }
1517                    clearDeliveredList = false;
1518                }
1519            }
1520        }
1521    }
1522
1523    public int getMessageSize() {
1524        return unconsumedMessages.size();
1525    }
1526
1527    public void start() throws JMSException {
1528        if (unconsumedMessages.isClosed()) {
1529            return;
1530        }
1531        started.set(true);
1532        unconsumedMessages.start();
1533        session.executor.wakeup();
1534    }
1535
1536    public void stop() {
1537        started.set(false);
1538        unconsumedMessages.stop();
1539    }
1540
1541    @Override
1542    public String toString() {
1543        return "ActiveMQMessageConsumer { value=" + info.getConsumerId() + ", started=" + started.get()
1544               + " }";
1545    }
1546
1547    /**
1548     * Delivers a message to the message listener.
1549     *
1550     * @return true if another execution is needed.
1551     *
1552     * @throws JMSException
1553     */
1554    public boolean iterate() {
1555        MessageListener listener = this.messageListener.get();
1556        if (listener != null) {
1557            MessageDispatch md = unconsumedMessages.dequeueNoWait();
1558            if (md != null) {
1559                dispatch(md);
1560                return true;
1561            }
1562        }
1563        return false;
1564    }
1565
1566    public boolean isInUse(ActiveMQTempDestination destination) {
1567        return info.getDestination().equals(destination);
1568    }
1569
1570    public long getLastDeliveredSequenceId() {
1571        return lastDeliveredSequenceId;
1572    }
1573
1574    public IOException getFailureError() {
1575        return failureError;
1576    }
1577
1578    public void setFailureError(IOException failureError) {
1579        this.failureError = failureError;
1580    }
1581
1582    /**
1583     * @return the optimizedAckScheduledAckInterval
1584     */
1585    public long getOptimizedAckScheduledAckInterval() {
1586        return optimizedAckScheduledAckInterval;
1587    }
1588
1589    /**
1590     * @param optimizedAckScheduledAckInterval the optimizedAckScheduledAckInterval to set
1591     */
1592    public void setOptimizedAckScheduledAckInterval(long optimizedAckScheduledAckInterval) throws JMSException {
1593        this.optimizedAckScheduledAckInterval = optimizedAckScheduledAckInterval;
1594
1595        if (this.optimizedAckTask != null) {
1596            try {
1597                this.session.connection.getScheduler().cancel(optimizedAckTask);
1598            } catch (JMSException e) {
1599                LOG.debug("Caught exception while cancelling old optimized ack task", e);
1600                throw e;
1601            }
1602            this.optimizedAckTask = null;
1603        }
1604
1605        // Should we periodically send out all outstanding acks.
1606        if (this.optimizeAcknowledge && this.optimizedAckScheduledAckInterval > 0) {
1607            this.optimizedAckTask = new Runnable() {
1608
1609                @Override
1610                public void run() {
1611                    try {
1612                        if (optimizeAcknowledge && !unconsumedMessages.isClosed()) {
1613                            LOG.info("Consumer:{} is performing scheduled delivery of outstanding optimized Acks", info.getConsumerId());
1614                            deliverAcks();
1615                        }
1616                    } catch (Exception e) {
1617                        LOG.debug("Optimized Ack Task caught exception during ack", e);
1618                    }
1619                }
1620            };
1621
1622            try {
1623                this.session.connection.getScheduler().executePeriodically(optimizedAckTask, optimizedAckScheduledAckInterval);
1624            } catch (JMSException e) {
1625                LOG.debug("Caught exception while scheduling new optimized ack task", e);
1626                throw e;
1627            }
1628        }
1629    }
1630
1631    public boolean hasMessageListener() {
1632        return messageListener.get() != null;
1633    }
1634
1635    public boolean isConsumerExpiryCheckEnabled() {
1636        return consumerExpiryCheckEnabled;
1637    }
1638
1639    public void setConsumerExpiryCheckEnabled(boolean consumerExpiryCheckEnabled) {
1640        this.consumerExpiryCheckEnabled = consumerExpiryCheckEnabled;
1641    }
1642}