Consistent Hashing
1. Introduction
Consistent Hashing is used for horizontal sharding, check here for mode details
2.Simple Version
Idea: Check the description in LintCode
Implementation: Lintcode Consistent Hashing
public List<List<Integer>> consistentHashing(int n) {
List<Integer> machine = new ArrayList<>();
machine.add(0);
machine.add(359);
machine.add(1);
res.add(machine);
for (int i = 1; i < n; i++) {
List<Integer> nextMachine = new ArrayList<>();
int index = 0;
// Look for the largest interval
for (int j = 1; j < i; j++) {
int nextInterval = res.get(j).get(1) - res.get(j).get(0) + 1;
int curInterval = res.get(index).get(1) - res.get(index).get(0) + 1;
if (curInterval < nextInterval) {
index = j;
}
}
// Divide the largest interval into havles
int start = res.get(index).get(0);
int end = res.get(index).get(1);
res.get(index).set(1, (start + end)/2);
// The other half will be assigned to the new machine
nextMachine.add((start + end)/2 + 1);
nextMachine.add(end);
nextMachine.add(i + 1);
res.add(nextMachine);
}
return res;
}3. Better version
Idea: Check the description in LintCode
Implementation: Lintcode Consistent Hashing II
Last updated
Was this helpful?