01: /*
02: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.l2.ha;
05:
06: import com.tc.util.Assert;
07:
08: import java.security.SecureRandom;
09: import java.util.ArrayList;
10: import java.util.List;
11:
12: public class WeightGeneratorFactory {
13:
14: private final List generators = new ArrayList();
15:
16: public static final WeightGenerator RANDOM_WEIGHT_GENERATOR = new WeightGenerator() {
17: public long getWeight() {
18: SecureRandom r = new SecureRandom();
19: return r.nextLong();
20: }
21: };
22:
23: public WeightGeneratorFactory() {
24: super ();
25: }
26:
27: public synchronized void add(WeightGenerator g) {
28: Assert.assertNotNull(g);
29: generators.add(g);
30: }
31:
32: public synchronized void remove(WeightGenerator g) {
33: Assert.assertNotNull(g);
34: generators.remove(g);
35: }
36:
37: public synchronized long[] generateWeightSequence() {
38: long weights[] = new long[generators.size()];
39: for (int i = 0; i < weights.length; i++) {
40: weights[i] = ((WeightGenerator) generators.get(0))
41: .getWeight();
42: }
43: return weights;
44: }
45:
46: public synchronized long[] generateMaxWeightSequence() {
47: long weights[] = new long[generators.size()];
48: for (int i = 0; i < weights.length; i++) {
49: weights[i] = Long.MAX_VALUE;
50: }
51: return weights;
52: }
53:
54: public static WeightGeneratorFactory createDefaultFactory() {
55: WeightGeneratorFactory wgf = new WeightGeneratorFactory();
56: wgf.add(RANDOM_WEIGHT_GENERATOR);
57: wgf.add(RANDOM_WEIGHT_GENERATOR);
58: return wgf;
59: }
60:
61: public static interface WeightGenerator {
62: public long getWeight();
63: }
64:
65: }
|