Skip to content

Instantly share code, notes, and snippets.

@JoshuaChi
Forked from bcambel/consist_hash.java
Created June 1, 2017 14:20
Show Gist options
  • Save JoshuaChi/5ee43fc690f59b07f5e5ce3463e8efb3 to your computer and use it in GitHub Desktop.
Save JoshuaChi/5ee43fc690f59b07f5e5ce3463e8efb3 to your computer and use it in GitHub Desktop.
Consistent Hash Java implementation
import java.util.Collection;
import java.util.SortedMap;
import java.util.TreeMap;
public class ConsistentHash<T> {
private final HashFunction hashFunction;
private final int numberOfReplicas;
private final SortedMap<Integer, T> circle = new TreeMap<Integer, T>();
public ConsistentHash(HashFunction hashFunction, int numberOfReplicas,
Collection<T> nodes) {
this.hashFunction = hashFunction;
this.numberOfReplicas = numberOfReplicas;
for (T node : nodes) {
add(node);
}
}
public void add(T node) {
for (int i = 0; i <numberOfReplicas; i++) {
circle.put(hashFunction.hash(node.toString() + i), node);
}
}
public void remove(T node) {
for (int i = 0; i <numberOfReplicas; i++) {
circle.remove(hashFunction.hash(node.toString() + i));
}
}
public T get(Object key) {
if (circle.isEmpty()) {
return null;
}
int hash = hashFunction.hash(key);
if (!circle.containsKey(hash)) {
SortedMap<Integer, T> tailMap = circle.tailMap(hash);
hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
}
return circle.get(hash);
}
}
@JoshuaChi
Copy link
Author

::get()
hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();

circle.firstKey() doesn't seem a good idea. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment