Created
January 14, 2020 01:08
-
-
Save smilingleo/852523da3a4a1e70ba52b3385c42fed6 to your computer and use it in GitHub Desktop.
Consistent hash by using Google Guava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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