提交 49ecc5d7 编写于 作者: K kohsuke

modified to gracefully handle the situation where there's no item in the hash

git-svn-id: https://hudson.dev.java.net/svn/hudson/trunk/hudson/main@17477 71c3de6d-444a-0410-be80-ed276b4c234a
上级 33848389
......@@ -120,7 +120,9 @@ public class ConsistentHash<T> {
}
T lookup(int queryPoint) {
return (T)owner[index(queryPoint)];
int i = index(queryPoint);
if(i<0) return null;
return (T)owner[i];
}
/**
......@@ -153,6 +155,7 @@ public class ConsistentHash<T> {
int idx = Arrays.binarySearch(hash, queryPoint);
if(idx<0) {
idx = -idx-1; // idx is now 'insertion point'
if(hash.length==0) return -1;
idx %= hash.length; // make it a circle
}
return idx;
......@@ -204,6 +207,7 @@ public class ConsistentHash<T> {
public ConsistentHash(Hash<T> hash, int defaultReplication) {
this.hash = hash;
this.defaultReplication = defaultReplication;
this.table = new Table(); // initial empty table
}
public int countAllPoints() {
......@@ -293,7 +297,7 @@ public class ConsistentHash<T> {
* or the # of replicas for the given node is changed.
*
* @return
* never null.
* null if the consistent hash is empty. Otherwise always non-null.
*/
public T lookup(int queryPoint) {
return table.lookup(queryPoint);
......
......@@ -112,4 +112,11 @@ public class ConsistentHashTest extends TestCase {
assertTrue(e.getValue()==0 || e.getValue()==m);
}
}
public void testEmptyBehavior() {
ConsistentHash<String> hash = new ConsistentHash<String>();
assertFalse(hash.list(0).iterator().hasNext());
assertNull(hash.lookup(0));
assertNull(hash.lookup(999));
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册