9ebf21cdcec1be10479cc5674219455fae42502b
[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
9 package org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy;
10
11 import java.util.Collection;
12 import java.util.Map;
13
14 /**
15  * The LeastLoadedCandidateSelectionStrategy assigns ownership for an entity to the candidate which owns the least
16  * number of entities.
17  */
18 public class LeastLoadedCandidateSelectionStrategy extends AbstractEntityOwnerSelectionStrategy {
19     protected LeastLoadedCandidateSelectionStrategy(long selectionDelayInMillis) {
20         super(selectionDelayInMillis);
21     }
22
23     @Override
24     public String newOwner(Collection<String> viableCandidates, Map<String, Long> statistics) {
25         String leastLoadedCandidate = null;
26         long leastLoadedCount = Long.MAX_VALUE;
27
28         for(String candidateName : viableCandidates){
29             Long val = statistics.get(candidateName);
30             if(val != null && val < leastLoadedCount){
31                 leastLoadedCount = val;
32                 leastLoadedCandidate = candidateName;
33             }
34         }
35
36         if(leastLoadedCandidate == null){
37             return viableCandidates.iterator().next();
38         }
39         return leastLoadedCandidate;
40     }
41 }