Skip to content

Instantly share code, notes, and snippets.

@smilingleo
Created January 14, 2020 01:08
Show Gist options
  • Save smilingleo/852523da3a4a1e70ba52b3385c42fed6 to your computer and use it in GitHub Desktop.
Save smilingleo/852523da3a4a1e70ba52b3385c42fed6 to your computer and use it in GitHub Desktop.
Consistent hash by using Google Guava
import com.google.common.hash.Hashing;
import org.junit.Test;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
public class HashingTest {
@Test
public void consistentHashing() {
int buckets = 3;
int tenants = 10;
Map<Integer, Set<Long>> output1 = new HashMap<>();
for (int i=0; i<tenants; i++) {
int output = Hashing.consistentHash(i, buckets);
output1.putIfAbsent(output, new LinkedHashSet<>());
output1.get(output).add(Long.valueOf(i));
}
System.out.println(output1);
// add a new bucket.
buckets = 4;
Map<Integer, Set<Long>> output2 = new HashMap<>();
for (int i=0; i<tenants; i++) {
int output = Hashing.consistentHash(i, buckets);
output2.putIfAbsent(output, new LinkedHashSet<>());
output2.get(output).add(Long.valueOf(i));
}
System.out.println(output2);
//{0=[0, 1, 2, 7, 8], 1=[4, 5], 2=[3, 6, 9]}
//{0=[0, 1, 7, 8], 1=[4, 5], 2=[6, 9], 3=[2, 3]}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment