2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy;
11 import com.google.common.base.MoreObjects;
12 import java.util.Collection;
13 import java.util.HashMap;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
19 * The LeastLoadedCandidateSelectionStrategy assigns ownership for an entity to the candidate which owns the least
22 public class LeastLoadedCandidateSelectionStrategy extends AbstractEntityOwnerSelectionStrategy {
23 private static final Logger LOG = LoggerFactory.getLogger(LeastLoadedCandidateSelectionStrategy.class);
25 private Map<String, Long> localStatistics = new HashMap<>();
27 protected LeastLoadedCandidateSelectionStrategy(long selectionDelayInMillis) {
28 super(selectionDelayInMillis);
32 public String newOwner(Collection<String> viableCandidates, Map<String, Long> statistics) {
33 String leastLoadedCandidate = null;
34 long leastLoadedCount = Long.MAX_VALUE;
36 for(String candidateName : viableCandidates){
37 long val = MoreObjects.firstNonNull(statistics.get(candidateName), 0L);
38 long localVal = MoreObjects.firstNonNull(localStatistics.get(candidateName), 0L);
40 LOG.debug("Local statistic higher - Candidate : {}, local statistic : {}, provided statistic : {}",
41 candidateName, localVal, val);
44 LOG.debug("Provided statistic higher - Candidate : {}, local statistic : {}, provided statistic : {}",
45 candidateName, localVal, val);
46 localStatistics.put(candidateName, val);
48 if(val < leastLoadedCount){
49 leastLoadedCount = val;
50 leastLoadedCandidate = candidateName;
54 if(leastLoadedCandidate == null){
55 leastLoadedCandidate = viableCandidates.iterator().next();
58 localStatistics.put(leastLoadedCandidate, leastLoadedCount + 1);
59 return leastLoadedCandidate;