001/* 002 * HA-JDBC: High-Availability JDBC 003 * Copyright (c) 2004-2007 Paul Ferraro 004 * 005 * This library is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Lesser General Public License as published by the 007 * Free Software Foundation; either version 2.1 of the License, or (at your 008 * option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, but WITHOUT 011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License 016 * along with this library; if not, write to the Free Software Foundation, 017 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018 * 019 * Contact: ferraro@users.sourceforge.net 020 */ 021package net.sf.hajdbc.balancer; 022 023import java.util.LinkedList; 024import java.util.Queue; 025 026import net.sf.hajdbc.Database; 027 028/** 029 * Balancer implementation whose {@link #next()} implementation uses a circular FIFO queue. 030 * 031 * @author Paul Ferraro 032 * @param <D> either java.sql.Driver or javax.sql.DataSource 033 */ 034public class RoundRobinBalancer<D> extends AbstractBalancer<D> 035{ 036 private Queue<Database<D>> databaseQueue = new LinkedList<Database<D>>(); 037 038 /** 039 * @see net.sf.hajdbc.balancer.AbstractBalancer#added(net.sf.hajdbc.Database) 040 */ 041 @Override 042 protected void added(Database<D> database) 043 { 044 int weight = database.getWeight(); 045 046 for (int i = 0; i < weight; ++i) 047 { 048 this.databaseQueue.add(database); 049 } 050 } 051 052 /** 053 * @see net.sf.hajdbc.balancer.AbstractBalancer#removed(net.sf.hajdbc.Database) 054 */ 055 @Override 056 protected void removed(Database<D> database) 057 { 058 int weight = database.getWeight(); 059 060 for (int i = 0; i < weight; ++i) 061 { 062 this.databaseQueue.remove(database); 063 } 064 } 065 066 /** 067 * @see net.sf.hajdbc.Balancer#next() 068 */ 069 @Override 070 public Database<D> next() 071 { 072 this.lock.lock(); 073 074 try 075 { 076 if (this.databaseQueue.isEmpty()) 077 { 078 return this.databaseSet.first(); 079 } 080 081 if (this.databaseQueue.size() == 1) 082 { 083 return this.databaseQueue.element(); 084 } 085 086 Database<D> database = this.databaseQueue.remove(); 087 088 this.databaseQueue.add(database); 089 090 return database; 091 } 092 finally 093 { 094 this.lock.unlock(); 095 } 096 } 097 098 /** 099 * @see net.sf.hajdbc.balancer.AbstractBalancer#cleared() 100 */ 101 @Override 102 protected void cleared() 103 { 104 this.databaseQueue.clear(); 105 } 106}