Refactor AbstractClientHandle a bit
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / 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.datastore.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(long selectionDelayInMillis, Map<String, Long> initialStatistics) {
26         super(selectionDelayInMillis, initialStatistics);
27
28         localStatistics.putAll(initialStatistics);
29     }
30
31     @Override
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;
36
37         if (!Strings.isNullOrEmpty(currentOwner)) {
38             long localVal = MoreObjects.firstNonNull(localStatistics.get(currentOwner), 0L);
39             localStatistics.put(currentOwner, localVal - 1);
40         }
41
42         for (String candidateName : viableCandidates) {
43             long val = MoreObjects.firstNonNull(localStatistics.get(candidateName), 0L);
44             if (val < leastLoadedCount) {
45                 leastLoadedCount = val;
46                 leastLoadedCandidate = candidateName;
47             }
48         }
49
50         if (leastLoadedCandidate == null) {
51             leastLoadedCandidate = viableCandidates.iterator().next();
52         }
53
54         localStatistics.put(leastLoadedCandidate, leastLoadedCount + 1);
55         return leastLoadedCandidate;
56     }
57
58     @VisibleForTesting
59     Map<String, Long> getLocalStatistics() {
60         return localStatistics;
61     }
62 }