1 19 package org.objectweb.carol.cmi; 20 21 import java.util.Collection ; 22 import java.util.Iterator ; 23 24 public class Random extends StubLB { 26 private ClusterStubData csd; 27 private int len; 28 private StubData[] sd; 29 30 34 public Random(ClusterStubData csd, Collection c) { 35 this.csd = csd; 36 len = c.size(); 37 sd = new StubData[len]; 38 Iterator it = c.iterator(); 39 for (int i = 0; i < len; i++) { 40 StubData s = (StubData) it.next(); 41 sd[i] = s; 42 } 43 } 44 45 private synchronized void ensureCapacity(int minCapacity) { 46 int old = sd.length; 47 if (old >= minCapacity) 48 return; 49 int l = (old * 3) / 2 + 1; 50 if (l < minCapacity) 51 l = minCapacity; 52 StubData[] nsd = new StubData[l]; 53 System.arraycopy(sd, 0, nsd, 0, old); 54 sd = nsd; 55 } 56 57 62 void add(StubData sd) { 63 ensureCapacity(len + 1); 64 this.sd[len] = sd; 65 len++; 66 } 67 68 73 void removeCallback(StubData s) { 74 for (int i = 0; i < len; i++) { 75 if (sd[i] == s) { 76 len--; 77 sd[i] = sd[len]; 78 sd[len] = null; 79 return; 80 } 81 } 82 } 83 84 public synchronized StubData get() throws NoMoreStubException { 85 if (len <= 0) { 86 throw new NoMoreStubException(); 87 } 88 int choice = SecureRandom.getInt(len); 89 return sd[choice]; 90 } 91 92 public synchronized StubData get(StubLBFilter f) throws NoMoreStubException { 93 int n = SecureRandom.getInt(len); 94 for (int i=0; i<len; i++) { 95 StubData s = sd[n]; 96 if (!f.contains(s)) { 97 return s; 98 } 99 n = (n + 1) % len; 100 } 101 throw new NoMoreStubException(); 102 } 103 104 107 public void remove(StubData s) { 108 csd.removeStubData(s); 109 } 110 } 111 | Popular Tags |