-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoadBalancerTask.java
41 lines (29 loc) · 1.54 KB
/
LoadBalancerTask.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package SystemDesign;
import java.util.SortedMap;
import java.util.concurrent.ThreadLocalRandom;
public class LoadBalancerTask implements Runnable {
final SortedMap<Integer, String> bucketIdToServer;
final ConsistentHashing.HashFunction hashFunction;
public LoadBalancerTask(final SortedMap<Integer, String> bucketIdToServer, final ConsistentHashing.HashFunction hashFunction) {
this.bucketIdToServer = bucketIdToServer;
this.hashFunction = hashFunction;
}
@Override
public void run() {
while (true) {
final int randomUserId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
final int userBucket = hashFunction.getHashValue(String.valueOf(randomUserId));
final SortedMap<Integer,String> mapViewWithKeyGreaterThanUserBucket = bucketIdToServer.tailMap(userBucket);
final Integer bucketIdWhichWillHandleTheUser = mapViewWithKeyGreaterThanUserBucket.isEmpty() ?
bucketIdToServer.firstKey() : mapViewWithKeyGreaterThanUserBucket.firstKey();
final String serverWhichWillHandleTheUser = bucketIdToServer.get(bucketIdWhichWillHandleTheUser);
System.out.println("--------------------------------------------------------------------------");
System.out.println("User ID : " + randomUserId + " has been assigned to " + serverWhichWillHandleTheUser);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}