Skip to content

Commit

Permalink
use a bit spreader!
Browse files Browse the repository at this point in the history
  • Loading branch information
maniksurtani committed Jan 28, 2010
1 parent 0ff3a6f commit a1faa91
Showing 1 changed file with 17 additions and 5 deletions.
Expand Up @@ -7,12 +7,13 @@
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import static java.lang.Math.min;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import static java.lang.Math.min;

@Marshallable(externalizer = DefaultConsistentHash.Externalizer.class, id = Ids.DEFAULT_CONSISTENT_HASH)
public class DefaultConsistentHash extends AbstractConsistentHash {

Expand All @@ -22,6 +23,17 @@ public class DefaultConsistentHash extends AbstractConsistentHash {

final static int HASH_SPACE = 10240; // no more than 10k nodes?

private int hash(Object o) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
int h = o.hashCode();
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}

public void setCaches(List<Address> caches) {

Expand All @@ -33,7 +45,7 @@ public void setCaches(List<Address> caches) {
positions = new TreeMap<Integer, Address>();

for (Address a : addresses) {
int positionIndex = Math.abs(a.hashCode()) % HASH_SPACE;
int positionIndex = Math.abs(hash(a.hashCode())) % HASH_SPACE;
// this is deterministic since the address list is ordered and the order is consistent across the grid
while (positions.containsKey(positionIndex)) positionIndex = positionIndex + 1 % HASH_SPACE;
positions.put(positionIndex, a);
Expand All @@ -49,7 +61,7 @@ public List<Address> getCaches() {
}

public List<Address> locate(Object key, int replCount) {
int keyHashCode = key.hashCode();
int keyHashCode = hash(key.hashCode());
if (keyHashCode == Integer.MIN_VALUE) keyHashCode += 1;
int hash = Math.abs(keyHashCode);
int numCopiesToFind = min(replCount, addresses.size());
Expand Down Expand Up @@ -86,7 +98,7 @@ public List<Address> locate(Object key, int replCount) {
@Override
public boolean isKeyLocalToAddress(Address target, Object key, int replCount) {
// more efficient impl
int keyHashCode = key.hashCode();
int keyHashCode = hash(key.hashCode());
if (keyHashCode == Integer.MIN_VALUE) keyHashCode += 1;
int hash = Math.abs(keyHashCode);
int numCopiesToFind = min(replCount, addresses.size());
Expand All @@ -113,7 +125,7 @@ public boolean isKeyLocalToAddress(Address target, Object key, int replCount) {
}
}
}

return false;
}

Expand Down

0 comments on commit a1faa91

Please sign in to comment.