1. 程式人生 > >按權重分配任務

按權重分配任務

static .get hash HA ati != 最大 red atom

public class TaskAlloc {

    private Map<String, Integer> weight;

    public Map<String, Integer> getWeight() {
        return weight;
    }

    public Map<String, Integer> getCmpltedTask() {
        return cmpltedTask;
    }

    public AtomicInteger getAllcodCount() {
        
return allcodCount; } private Map<String, Integer> cmpltedTask = new ConcurrentHashMap<String, Integer>(); private AtomicInteger allcodCount = new AtomicInteger(0); public TaskAlloc(Map<String, Integer> weight) throws Exception { this.weight = weight; Integer sum
= MapHelper.reduce(weight, 0, (init, current) -> init + current); if (sum != 100) { throw new Exception("權重之合必須為100"); } for (String key : weight.keySet()) { cmpltedTask.put(key, 0); } } public String alloc() { int ac = allcodCount.getAndIncrement(); String key
= getMin(cmpltedTask, weight, ac); cmpltedTask.put(key, cmpltedTask.get(key) + 1); return key; } private static String getMin(Map<String, Integer> allocedRecordMap, Map<String, Integer> weightMap, Integer allocedCount) { double min = 1; String result = null; for (Map.Entry<String, Integer> entry : weightMap.entrySet()) { String key = entry.getKey(); //計算權重所占最大的比例 double maxRatio = entry.getValue() * 1.0 / 100; //計算已分配的比例 double cmpltedRatio = allocedCount == 0 ? 0 : allocedRecordMap.get(key) * 1.0 / allocedCount; double ratio = cmpltedRatio / maxRatio; if (ratio < min) { result = key; min = ratio; } } return result; } }

按權重分配任務