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 import java.io.Serializable; 019 020 /** 021 * RoundRobinConnectionLoadBalancingPolicy corresponds to a round-robin load-balancing policy. 022 * 023 * <br> 024 * The first call to {@link #select(int)} will return a random integer between {@code 0} (inclusive) and {@code max} (exclusive). 025 * Subsequent calls will then return an integer in a round-robin fashion. 026 * 027 * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a> 028 * 029 * Created 28 Nov 2008 10:21:08 030 * 031 * 032 */ 033 public class RoundRobinConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy, Serializable 034 { 035 private static final long serialVersionUID = 7511196010141439559L; 036 037 private final Random random = new Random(); 038 039 private boolean first = true; 040 041 private int pos; 042 043 public int select(final int max) 044 { 045 if (first) 046 { 047 // We start on a random one 048 pos = random.getRandom().nextInt(max); 049 050 first = false; 051 } 052 else 053 { 054 pos++; 055 056 if (pos >= max) 057 { 058 pos = 0; 059 } 060 } 061 062 return pos; 063 } 064 }