int highIndex = -1;
double highLoad = 0.0;
double load = 0.0;
for (int i = 0, size = bucket.assignedAgents.size(); (i < size); ++i) {
Agent agent = bucket.assignedAgents.get(i);
// we don't move an agent with satisfied affinity to a bucket that breaks affinity
if (checkAffinity && affinityGroup.equals(agent.getAffinityGroup())) {
continue;
}
// we don't move an agent that is already assigned to lowBucket
if (agentServerListMap.get(agent).contains(lowBucket)) {
continue;
}
load = getAgentLoad(agent);
if (load > highLoad) {
// protect against a move that would send too much load to the lowBucket, effectively just
// reversing the problem and allowing this algorithm to thrash. Don't allow a move that
// increases the lowBucket load higher than the current bucket.
if (!((lowBucket.assignedLoad + load) > (bucket.assignedLoad - load))) {
highIndex = i;
highLoad = load;
}
}
}
// If we found an agent to move then make the move, otherwise look in the next bucket
if (highIndex > -1) {
Agent agent = bucket.assignedAgents.remove(highIndex);
lowBucket.assignedAgents.add(agent);
agentServerListMap.get(agent).remove(bucket);
agentServerListMap.get(agent).add(lowBucket);
lowBucket.assignedLoad += highLoad;
bucket.assignedLoad -= highLoad;