Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

/**
Expand All @@ -30,7 +31,7 @@
* algorithm
*/
public class ConsistentHashRouter<T extends Node> {
private final SortedMap<Long, VirtualNode<T>> ring = new TreeMap<>();
private final NavigableMap<Long, VirtualNode<T>> ring = new TreeMap<>();
private final HashFunction hashFunction;

public ConsistentHashRouter(Collection<T> pNodes, int vNodeCount) {
Expand Down Expand Up @@ -94,9 +95,11 @@ public T routeNode(String objectKey) {
return null;
}
Long hashVal = hashFunction.hash(objectKey);
SortedMap<Long, VirtualNode<T>> tailMap = ring.tailMap(hashVal);
Long nodeHashVal = !tailMap.isEmpty() ? tailMap.firstKey() : ring.firstKey();
return ring.get(nodeHashVal).getPhysicalNode();
Map.Entry<Long, VirtualNode<T>> entry = ring.ceilingEntry(hashVal);
if (entry == null) {
entry = ring.firstEntry();
}
return entry.getValue().getPhysicalNode();
}

public int getExistingReplicas(T pNode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,41 @@ public void testEmptyRingHasNoRoute() {

assertNull(router.routeNode("message-queue"));
}

@Test
public void testRouteAcrossSignedHashRange() {
Node first = () -> "first";
Node last = () -> "last";
HashFunction hash = key -> {
if ("first-0".equals(key)) {
return Long.MIN_VALUE + 1;
}
if ("last-0".equals(key)) {
return Long.MAX_VALUE - 1;
}
return Long.parseLong(key);
};
ConsistentHashRouter<Node> router = new ConsistentHashRouter<>(Arrays.asList(first, last), 1, hash);

assertSame(first, router.routeNode(Long.toString(Long.MIN_VALUE)));
assertSame(first, router.routeNode(Long.toString(Long.MIN_VALUE + 1)));
assertSame(last, router.routeNode("0"));
assertSame(last, router.routeNode(Long.toString(Long.MAX_VALUE - 1)));
assertSame(first, router.routeNode(Long.toString(Long.MAX_VALUE)));
}

@Test
public void testRouteAfterHashCollisionAndRemoval() {
Node first = () -> "first";
Node replacement = () -> "replacement";
ConsistentHashRouter<Node> router = new ConsistentHashRouter<>(
Collections.singletonList(first), 1, key -> 10L);

router.addNode(replacement, 1);
assertSame(replacement, router.routeNode("queue"));
router.removeNode(first);
assertSame(replacement, router.routeNode("queue"));
router.removeNode(replacement);
assertNull(router.routeNode("queue"));
}
}
Loading