01: /*
02: * HA-JDBC: High-Availability JDBC
03: * Copyright (c) 2004-2007 Paul Ferraro
04: *
05: * This library is free software; you can redistribute it and/or modify it
06: * under the terms of the GNU Lesser General Public License as published by the
07: * Free Software Foundation; either version 2.1 of the License, or (at your
08: * option) any later version.
09: *
10: * This library is distributed in the hope that it will be useful, but WITHOUT
11: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
13: * for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public License
16: * along with this library; if not, write to the Free Software Foundation,
17: * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18: *
19: * Contact: ferraro@users.sourceforge.net
20: */
21: package net.sf.hajdbc.balancer;
22:
23: import java.util.LinkedList;
24: import java.util.Queue;
25:
26: import net.sf.hajdbc.Database;
27:
28: /**
29: * Balancer implementation whose {@link #next()} implementation uses a circular FIFO queue.
30: *
31: * @author Paul Ferraro
32: * @param <D> either java.sql.Driver or javax.sql.DataSource
33: */
34: public class RoundRobinBalancer<D> extends AbstractBalancer<D> {
35: private Queue<Database<D>> databaseQueue = new LinkedList<Database<D>>();
36:
37: /**
38: * @see net.sf.hajdbc.balancer.AbstractBalancer#added(net.sf.hajdbc.Database)
39: */
40: @Override
41: protected void added(Database<D> database) {
42: int weight = database.getWeight();
43:
44: for (int i = 0; i < weight; ++i) {
45: this .databaseQueue.add(database);
46: }
47: }
48:
49: /**
50: * @see net.sf.hajdbc.balancer.AbstractBalancer#removed(net.sf.hajdbc.Database)
51: */
52: @Override
53: protected void removed(Database<D> database) {
54: int weight = database.getWeight();
55:
56: for (int i = 0; i < weight; ++i) {
57: this .databaseQueue.remove(database);
58: }
59: }
60:
61: /**
62: * @see net.sf.hajdbc.Balancer#next()
63: */
64: @Override
65: public Database<D> next() {
66: this .lock.lock();
67:
68: try {
69: if (this .databaseQueue.isEmpty()) {
70: return this .databaseSet.first();
71: }
72:
73: if (this .databaseQueue.size() == 1) {
74: return this .databaseQueue.element();
75: }
76:
77: Database<D> database = this .databaseQueue.remove();
78:
79: this .databaseQueue.add(database);
80:
81: return database;
82: } finally {
83: this .lock.unlock();
84: }
85: }
86:
87: /**
88: * @see net.sf.hajdbc.balancer.AbstractBalancer#cleared()
89: */
90: @Override
91: protected void cleared() {
92: this.databaseQueue.clear();
93: }
94: }
|