0
点赞
收藏
分享

微信扫一扫

某程序员哀叹:二本计算机,4年开发,年包才40多万。二本真的不如985/211吗?

Hyggelook 2023-05-05 阅读 63
java
public class IdGenerator {

    private static volatile Snowflake snowflake = new Snowflake();

    public static synchronized String nextId() {
        return String.valueOf(snowflake.nextId());
    }

    private static class Snowflake {
        private static final long START_TIME = 1672502400000L; // 22023-01-01 00:00:00 UTC
        private static final int DATA_CENTER_ID_BITS = 5;
        private static final int MACHINE_ID_BITS = 5;
        private static final int SEQUENCE_BITS = 12;
        private static final int MAX_DATA_CENTER_ID = ~(-1 << DATA_CENTER_ID_BITS);
        private static final int MAX_MACHINE_ID = ~(-1 << MACHINE_ID_BITS);
        private static final int MAX_SEQUENCE = ~(-1 << SEQUENCE_BITS);
        private static final int MACHINE_ID_SHIFT = SEQUENCE_BITS;
        private static final int DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS;
        private static final int TIMESTAMP_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS + DATA_CENTER_ID_BITS;
        private final int dataCenterId = 6;
        private final int machineId = 8;
        private long lastTimestamp = -1L;
        private int sequence = 0;


        public synchronized long nextId() {
            long timestamp = System.currentTimeMillis();
            if (timestamp < lastTimestamp) {
                throw new RuntimeException("Clock moved backwards, refusing to generate ID");
            }
            if (timestamp == lastTimestamp) {
                sequence = (sequence + 1) & MAX_SEQUENCE;
                if (sequence == 0) {
                    // Sequence exhausted, wait for the next millisecond
                    timestamp = waitNextMillis(timestamp);
                }
            } else {
                sequence = 0;
            }
            lastTimestamp = timestamp;
            return ((timestamp - START_TIME) << TIMESTAMP_SHIFT)
                    | (dataCenterId << DATA_CENTER_ID_SHIFT)
                    | (machineId << MACHINE_ID_SHIFT)
                    | sequence;
        }

        private long waitNextMillis(long timestamp) {
            while (timestamp == lastTimestamp) {
                timestamp = System.currentTimeMillis();
            }
            return timestamp;
        }
    }
}
举报

相关推荐

0 条评论