DynamicLoadBalanceFactorProvider implements LoadBalanceFactorProvider, DynamicLoadBalanceFactorProviderMBean { @Override public synchronized int getLoadBalanceFactor(Engine engine) { boolean nodeUnavailable = false; int totalWeight = 0; double totalWeightedLoad = 0; for (Map.Entry<LoadMetric, List<Double>> entry : this.loadHistory.entrySet()) { LoadMetric metric = entry.getKey(); int weight = metric.getWeight(); if (weight > 0) { List<Double> metricLoadHistory = entry.getValue(); try { this.recordLoad(metricLoadHistory, metric.getLoad(engine) / metric.getCapacity()); totalWeight += weight; totalWeightedLoad += this.average(metricLoadHistory) * weight; } catch (NodeUnavailableException e) { nodeUnavailable = true; } catch (Exception e) { this.log.error(e.getLocalizedMessage(), e); } } } if (nodeUnavailable) { return -1; } int load = (int) Math.round(100 * totalWeightedLoad / totalWeight); return 100 - Math.max(0, Math.min(load, 99)); } DynamicLoadBalanceFactorProvider(Set<LoadMetric> metrics);  DynamicLoadBalanceFactorProvider(Set<LoadMetric> metrics, int initialLoad); @Override synchronized Map<String, Double> getMetrics(); @Override synchronized int getLoadBalanceFactor(Engine engine); @Override float getDecayFactor(); @Override void setDecayFactor(float decayFactor); @Override int getHistory(); @Override void setHistory(int history); static final int DEFAULT_INITIAL_LOAD; static final float DEFAULT_DECAY_FACTOR; static final int DEFAULT_HISTORY; }
@Test public void getLoadBalanceFactor() throws Exception { Engine engine = mock(Engine.class); Set<LoadMetric> metrics = new HashSet<>(); LoadMetric metric = mock(LoadMetric.class); when(metric.getWeight()).thenReturn(LoadMetric.DEFAULT_WEIGHT); when(metric.getLoad(engine)).thenThrow(new NodeUnavailableException()); metrics.add(metric); DynamicLoadBalanceFactorProvider provider = new DynamicLoadBalanceFactorProvider(metrics); int loadBalanceFactor = provider.getLoadBalanceFactor(engine); assertEquals(-1, loadBalanceFactor); }