Fixup checkstyle
[controller.git] / opendaylight / md-sal / sal-distributed-eos / src / main / java / org / opendaylight / controller / cluster / entityownership / selectionstrategy / LeastLoadedCandidateSelectionStrategy.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.entityownership.selectionstrategy;
9
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;
16 import java.util.Map;
17
18 /**
19  * The LeastLoadedCandidateSelectionStrategy assigns ownership for an entity to the candidate which owns the least
20  * number of entities.
21  */
22 public class LeastLoadedCandidateSelectionStrategy extends AbstractEntityOwnerSelectionStrategy {
23     private final Map<String, Long> localStatistics = new HashMap<>();
24
25     protected LeastLoadedCandidateSelectionStrategy(final long selectionDelayInMillis,
26             final Map<String, Long> initialStatistics) {
27         super(selectionDelayInMillis, initialStatistics);
28
29         localStatistics.putAll(initialStatistics);
30     }
31
32     @Override
33     public String newOwner(final String currentOwner, final Collection<String> viableCandidates) {
34         Preconditions.checkArgument(viableCandidates.size() > 0);
35         String leastLoadedCandidate = null;
36         long leastLoadedCount = Long.MAX_VALUE;
37
38         if (!Strings.isNullOrEmpty(currentOwner)) {
39             long localVal = MoreObjects.firstNonNull(localStatistics.get(currentOwner), 0L);
40             localStatistics.put(currentOwner, localVal - 1);
41         }
42
43         for (String candidateName : viableCandidates) {
44             long val = MoreObjects.firstNonNull(localStatistics.get(candidateName), 0L);
45             if (val < leastLoadedCount) {
46                 leastLoadedCount = val;
47                 leastLoadedCandidate = candidateName;
48             }
49         }
50
51         if (leastLoadedCandidate == null) {
52             leastLoadedCandidate = viableCandidates.iterator().next();
53         }
54
55         localStatistics.put(leastLoadedCandidate, leastLoadedCount + 1);
56         return leastLoadedCandidate;
57     }
58
59     @VisibleForTesting
60     Map<String, Long> getLocalStatistics() {
61         return localStatistics;
62     }
63 }