### Question:
LatencyWeightedRouter { public R getRoute() { synchronized (pq) { while (!pq.isEmpty()) { R route = pq.poll(); if (!route.isClosed()) { route.updateWeight(); pq.offer(route); return route; } } return null; } } LatencyWeightedRouter(Collection<R> routes); R getRoute(); static final long MAX_LATENCY; static final long DEFAULT_LATENCY; }### Answer:
@Test public void testEvenRouting() { MockLatencyWeightedRoute lastRoute = null; for (int i = 0; i < REPEAT; i++) { MockLatencyWeightedRoute route = router.getRoute(); assertNotEquals(lastRoute, route); if (route != null) { route.incr(); route.updateExpectedLatency(10); lastRoute = route; } else { fail(); } } double expected = 1.0 / (double) NUM_ROUTES; for (MockLatencyWeightedRoute route : routes) { assertTrue(Math.abs((double) route.count() / (double) REPEAT - expected) < 0.01); } }
@Test public void testSkewedRouting() { Map<MockLatencyWeightedRoute, Long> latencyMap = new IdentityHashMap<>(); long latency = 100L; double sum = 0.0; for (MockLatencyWeightedRoute route : routes) { latencyMap.put(route, latency); sum += 1.0 / (double) latency; latency *= 2; } Map<MockLatencyWeightedRoute, Double> ratioMap = new IdentityHashMap<>(); for (Map.Entry<MockLatencyWeightedRoute, Long> entry : latencyMap.entrySet()) { ratioMap.put(entry.getKey(), (1.0 / (double) entry.getValue()) / sum); } for (int i = 0; i < REPEAT; i++) { MockLatencyWeightedRoute route = router.getRoute(); if (route != null) { route.incr(); route.updateExpectedLatency(latencyMap.get(route)); } else { fail(); } } for (MockLatencyWeightedRoute route : routes) { assertTrue(Math.abs((double) route.count() / (double) REPEAT - ratioMap.get(route)) < 0.01); } }