1 21 package net.sf.hajdbc.balancer; 22 23 import java.util.ArrayList ; 24 import java.util.Collection ; 25 import java.util.Collections ; 26 import java.util.Comparator ; 27 import java.util.HashMap ; 28 import java.util.List ; 29 import java.util.Map ; 30 31 import net.sf.hajdbc.Database; 32 33 37 public class LoadBalancer extends AbstractBalancer 38 { 39 private Map <Database, Integer > databaseMap = new HashMap <Database, Integer >(); 40 41 44 @Override 45 protected Collection <Database> getDatabases() 46 { 47 return this.databaseMap.keySet(); 48 } 49 50 53 @Override 54 public synchronized boolean add(Database database) 55 { 56 boolean exists = this.databaseMap.containsKey(database); 57 58 if (!exists) 59 { 60 this.databaseMap.put(database, 1); 61 } 62 63 return !exists; 64 } 65 66 69 public synchronized Database next() 70 { 71 if (this.databaseMap.size() <= 1) 72 { 73 return this.first(); 74 } 75 76 List <Map.Entry <Database, Integer >> databaseMapEntryList = new ArrayList <Map.Entry <Database, Integer >>(this.databaseMap.entrySet()); 77 78 Collections.sort(databaseMapEntryList, comparator); 79 80 Map.Entry <Database, Integer > mapEntry = databaseMapEntryList.get(0); 81 82 return mapEntry.getKey(); 83 } 84 85 88 @Override 89 public void beforeOperation(Database database) 90 { 91 this.incrementLoad(database, 1); 92 } 93 94 97 @Override 98 public void afterOperation(Database database) 99 { 100 this.incrementLoad(database, -1); 101 } 102 103 private synchronized void incrementLoad(Database database, int increment) 104 { 105 Integer load = this.databaseMap.remove(database); 106 107 if (load != null) 108 { 109 this.databaseMap.put(database, load + increment); 110 } 111 } 112 113 private static Comparator <Map.Entry <Database, Integer >> comparator = new Comparator <Map.Entry <Database, Integer >>() 114 { 115 public int compare(Map.Entry <Database, Integer > mapEntry1, Map.Entry <Database, Integer > mapEntry2) 116 { 117 Database database1 = mapEntry1.getKey(); 118 Database database2 = mapEntry2.getKey(); 119 120 Integer load1 = mapEntry1.getValue(); 121 Integer load2 = mapEntry2.getValue(); 122 123 int weight1 = database1.getWeight(); 124 int weight2 = database2.getWeight(); 125 126 if (weight1 == weight2) 127 { 128 return load1.compareTo(load2); 129 } 130 131 float weightedLoad1 = (weight1 != 0) ? (load1.floatValue() / weight1) : Float.POSITIVE_INFINITY; 132 float weightedLoad2 = (weight2 != 0) ? (load2.floatValue() / weight2) : Float.POSITIVE_INFINITY; 133 134 return Float.compare(weightedLoad1, weightedLoad2); 135 } 136 }; 137 } 138 | Popular Tags |