001: package distributedcache;
002:
003: import java.util.HashMap;
004: import java.util.Map;
005:
006: import org.xsocket.group.Address;
007:
008: final class DistributionList {
009:
010: private static final int DEFAULT_SLOT_COUNT = 1000;
011:
012: private int slotCount = DEFAULT_SLOT_COUNT;
013:
014: private final Map<Integer, Slot> slots = new HashMap<Integer, Slot>();
015:
016: public synchronized boolean addAddress(Address address) {
017: if (slots.isEmpty()) {
018: for (int i = 0; i < slotCount; i++) {
019: slots.put(i, new Slot(address, address));
020: }
021: return true;
022:
023: } else {
024: Map<Address, Integer> primaries = new HashMap<Address, Integer>();
025: Map<Address, Integer> secondaries = new HashMap<Address, Integer>();
026: for (Slot slot : slots.values()) {
027: if (primaries.containsKey(slot.getPrimary())) {
028: int i = primaries.get(slot.getPrimary());
029: i++;
030: primaries.put(slot.getPrimary(), i);
031: } else {
032: primaries.put(slot.getPrimary(), 1);
033: }
034: }
035:
036: for (Slot slot : slots.values()) {
037: if (secondaries.containsKey(slot.getSecondary())) {
038: int i = secondaries.get(slot.getSecondary());
039: i++;
040: secondaries.put(slot.getSecondary(), i);
041: } else {
042: secondaries.put(slot.getSecondary(), 1);
043: }
044: }
045:
046: if (primaries.containsKey(address)) {
047: return false;
048: }
049:
050: return true;
051: }
052: }
053:
054: public synchronized Address getPrimary(Object key) {
055: Slot slot = slots.get(computeSlotNumber(key));
056:
057: if (slot == null) {
058: return null;
059: } else {
060: return slot.primary;
061: }
062: }
063:
064: public synchronized Address getSecondaryPrimary(Object key) {
065: Slot slot = slots.get(computeSlotNumber(key));
066:
067: if (slot == null) {
068: return null;
069: } else {
070: return slot.secondary;
071: }
072: }
073:
074: private int computeSlotNumber(Object key) {
075: int hashCode = key.hashCode();
076: if (hashCode < 0) {
077: hashCode *= -1;
078: }
079:
080: return hashCode % slotCount;
081: }
082:
083: private static final class Slot {
084: private Address primary = null;
085: private Address secondary = null;
086:
087: Slot(Address primary, Address secondary) {
088: this .primary = primary;
089: this .secondary = secondary;
090: }
091:
092: public Address getPrimary() {
093: return primary;
094: }
095:
096: public Address getSecondary() {
097: return secondary;
098: }
099: }
100: }
|