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.Collections;
24: import java.util.Comparator;
25: import java.util.NoSuchElementException;
26:
27: import net.sf.hajdbc.Database;
28:
29: /**
30: * Trivial balancer implementation whose {@link #next} implementation always returns the database with the highest weight.
31: *
32: * @author Paul Ferraro
33: * @param <D> either java.sql.Driver or javax.sql.DataSource
34: */
35: public class SimpleBalancer<D> extends AbstractBalancer<D> {
36: private volatile Database<D> nextDatabase = null;
37:
38: private Comparator<Database<D>> comparator = new Comparator<Database<D>>() {
39: @Override
40: public int compare(Database<D> database1, Database<D> database2) {
41: return database1.getWeight() - database2.getWeight();
42: }
43: };
44:
45: /**
46: * @see net.sf.hajdbc.Balancer#next()
47: */
48: @Override
49: public Database<D> next() {
50: Database<D> next = this .nextDatabase;
51:
52: if (next == null) {
53: throw new NoSuchElementException();
54: }
55:
56: return next;
57: }
58:
59: /**
60: * @see net.sf.hajdbc.balancer.AbstractBalancer#added(net.sf.hajdbc.Database)
61: */
62: @Override
63: protected void added(Database<D> database) {
64: this .reset();
65: }
66:
67: /**
68: * @see net.sf.hajdbc.balancer.AbstractBalancer#removed(net.sf.hajdbc.Database)
69: */
70: @Override
71: protected void removed(Database<D> database) {
72: this .reset();
73: }
74:
75: private void reset() {
76: this .nextDatabase = this .databaseSet.isEmpty() ? null
77: : Collections.max(this .databaseSet, this .comparator);
78: }
79:
80: /**
81: * @see net.sf.hajdbc.balancer.AbstractBalancer#cleared()
82: */
83: @Override
84: protected void cleared() {
85: this.nextDatabase = null;
86: }
87: }
|