001    /*
002     * Copyright 2009 Red Hat, Inc.
003     * Red Hat licenses this file to you under the Apache License, version
004     * 2.0 (the "License"); you may not use this file except in compliance
005     * with the License.  You may obtain a copy of the License at
006     *    http://www.apache.org/licenses/LICENSE-2.0
007     * Unless required by applicable law or agreed to in writing, software
008     * distributed under the License is distributed on an "AS IS" BASIS,
009     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
010     * implied.  See the License for the specific language governing
011     * permissions and limitations under the License.
012     */
013    
014    package org.hornetq.api.core.client.loadbalance;
015    
016    import org.hornetq.utils.Random;
017    
018    /**
019     * RoundRobinConnectionLoadBalancingPolicy corresponds to a round-robin load-balancing policy.
020     *
021     * <br>
022     * The first call to {@link #select(int)} will return a random integer between {@code 0} (inclusive) and {@code max} (exclusive).
023     * Subsequent calls will then return an integer in a round-robin fashion.
024     *
025     * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
026     *
027     * Created 28 Nov 2008 10:21:08
028     *
029     *
030     */
031    public class RoundRobinConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy
032    {
033       private final Random random = new Random();
034    
035       private boolean first = true;
036    
037       private int pos;
038    
039       public int select(final int max)
040       {
041          if (first)
042          {
043             // We start on a random one
044             pos = random.getRandom().nextInt(max);
045    
046             first = false;
047          }
048          else
049          {
050             pos++;
051    
052             if (pos >= max)
053             {
054                pos = 0;
055             }
056          }
057    
058          return pos;
059       }
060    }