All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.linmoure.algorithm.AbstractAlgorithm Maven / Gradle / Ivy

There is a newer version: 1.1.1
Show newest version
package io.github.linmoure.algorithm;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 李衡林
 */
public abstract class AbstractAlgorithm {

    private static final AtomicInteger NEXT_SERVER_CYCLIC_COUNTER = new AtomicInteger(0);

    /**
     * 随机算法
     *
     * @param num 数量
     * @return 随机资源
     */
    public int chooseRandomInt(int num) {
        return ThreadLocalRandom.current().nextInt(num);
    }

    /**
     * 轮询取模算法
     *
     * @param num 数量
     * @return 轮询
     */
    public static int incrementAndGetModulo(int num) {
        int current;
        int next;
        do {
            current = NEXT_SERVER_CYCLIC_COUNTER.get();
            next = (current + 1) % num;
        } while (!NEXT_SERVER_CYCLIC_COUNTER.compareAndSet(current, next));
        return next;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy