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.policy; 018 019import java.util.Iterator; 020import java.util.List; 021import org.apache.activemq.broker.region.MessageReference; 022import org.apache.activemq.broker.region.Subscription; 023import org.apache.activemq.filter.MessageEvaluationContext; 024 025/** 026 * Simple dispatch policy that sends a message to every subscription that 027 * matches the message. 028 * 029 * @org.apache.xbean.XBean 030 * 031 */ 032public class RoundRobinDispatchPolicy implements DispatchPolicy { 033 034 /** 035 * @param node 036 * @param msgContext 037 * @param consumers 038 * @return true if dispatched 039 * @throws Exception 040 * @see org.apache.activemq.broker.region.policy.DispatchPolicy#dispatch(org.apache.activemq.broker.region.MessageReference, 041 * org.apache.activemq.filter.MessageEvaluationContext, java.util.List) 042 */ 043 public boolean dispatch(MessageReference node, 044 MessageEvaluationContext msgContext, List<Subscription> consumers) 045 throws Exception { 046 int count = 0; 047 048 Subscription firstMatchingConsumer = null; 049 synchronized (consumers) { 050 for (Iterator<Subscription> iter = consumers.iterator(); iter 051 .hasNext();) { 052 Subscription sub = iter.next(); 053 054 // Only dispatch to interested subscriptions 055 if (!sub.matches(node, msgContext)) { 056 sub.unmatched(node); 057 continue; 058 } 059 060 if (firstMatchingConsumer == null) { 061 firstMatchingConsumer = sub; 062 } 063 064 sub.add(node); 065 count++; 066 } 067 068 if (firstMatchingConsumer != null) { 069 // Rotate the consumer list. 070 try { 071 consumers.remove(firstMatchingConsumer); 072 consumers.add(firstMatchingConsumer); 073 } catch (Throwable bestEffort) { 074 } 075 } 076 } 077 return count > 0; 078 } 079}