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
8 package org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Strings;
14 import java.util.Collection;
15 import java.util.HashMap;
19 * The LeastLoadedCandidateSelectionStrategy assigns ownership for an entity to the candidate which owns the least
22 public class LeastLoadedCandidateSelectionStrategy extends AbstractEntityOwnerSelectionStrategy {
23 private final Map<String, Long> localStatistics = new HashMap<>();
25 protected LeastLoadedCandidateSelectionStrategy(long selectionDelayInMillis, Map<String, Long> initialStatistics) {
26 super(selectionDelayInMillis, initialStatistics);
28 localStatistics.putAll(initialStatistics);
32 public String newOwner(String currentOwner, Collection<String> viableCandidates) {
33 Preconditions.checkArgument(viableCandidates.size() > 0);
34 String leastLoadedCandidate = null;
35 long leastLoadedCount = Long.MAX_VALUE;
37 if (!Strings.isNullOrEmpty(currentOwner)) {
38 long localVal = MoreObjects.firstNonNull(localStatistics.get(currentOwner), 0L);
39 localStatistics.put(currentOwner, localVal - 1);
42 for (String candidateName : viableCandidates) {
43 long val = MoreObjects.firstNonNull(localStatistics.get(candidateName), 0L);
44 if (val < leastLoadedCount) {
45 leastLoadedCount = val;
46 leastLoadedCandidate = candidateName;
50 if (leastLoadedCandidate == null) {
51 leastLoadedCandidate = viableCandidates.iterator().next();
54 localStatistics.put(leastLoadedCandidate, leastLoadedCount + 1);
55 return leastLoadedCandidate;
59 Map<String, Long> getLocalStatistics() {
60 return localStatistics;