Java 代码生成字符串Id及Long类型的Id(源码解析)

import cn.hutool.core.date.SystemClock;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;

import java.util.*;


public static void main(String[] args) {
        //生成字符串随机数id
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid);//a0f61136-19a2-4cbb-8c41-c2cb7f734131
        //生成long类型 的id
        DefaultIdentifierGenerator defaultIdentifierGenerator = new DefaultIdentifierGenerator();
        Long aLong = defaultIdentifierGenerator.nextId(new Object().toString());
        System.out.println(aLong);//1602296057001435137
    }

    //defaultIdentifierGenerator对象的nextId 方法 底层 源码 
    public synchronized long nextId() {
        //通过timeGen() 方法获取当前毫米值
        long timestamp = this.timeGen();
        //lastTimestamp 初始化后的值 为-1
        if (timestamp < this.lastTimestamp) {
            //当获取的当前时间小于lastTimestamp 时间时  求取增量
            long offset = this.lastTimestamp - timestamp;
            if (offset > 5L) {
                throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", offset));
            }

            try {
                this.wait(offset << 1);
                timestamp = this.timeGen();
                if (timestamp < this.lastTimestamp) {
                    throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", offset));
                }
            } catch (Exception var6) {
                throw new RuntimeException(var6);
            }
        }

        if (this.lastTimestamp == timestamp) {
            this.sequence = this.sequence + 1L & 4095L;
            if (this.sequence == 0L) {
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {
            this.sequence = ThreadLocalRandom.current().nextLong(1L, 3L);
        }
        //将获取的当前毫秒值进行赋值
        this.lastTimestamp = timestamp;
        //对返回值 进行一些运算
        return timestamp - 1288834974657L << 22 | this.datacenterId << 17 | this.workerId << 12 | this.sequence;
    }
    
    //获取当前系统时间 方法
    protected long timeGen() {
        //获取当前时间方法 为什么 不使用 System.currentTimeMillis() 方法呢?
        return SystemClock.now();
    }
        //currentTimeMillis 方法是被 native 所修饰的在并发数量过高时会影响性能
        //SystemClock.now(); 是被volatile 所修饰的 保证可见性 不保证原子性 禁止指令重排
        public static native long currentTimeMillis();

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值