java id 生成器_[Java]IdWorker ID生成器

package cn.studyjava.util;

/**

* @author zsljava@163.com

* JavaScript整数最大支持53位

* 时间41位 机器号1位 毫秒ID自增6位 一共48位

*/

public class IdWorker {

/**

* 2016-01-01 00:00:00

*/

private final static long twepoch = 1451577600000L;

/**

* 机器标识位数

*/

private final static long workerIdBits = 1L;

/**

* 机器ID支持机器节点数0~1

*/

public final static long maxWorkerId = ~(-1L << workerIdBits);

/**

* 毫秒内自增位

*/

private final static long sequenceBits = 6L;

/**

* 毫秒内sequence范围0~63

*/

public final static long sequenceMask = ~(-1L << sequenceBits);

/**

* 机器ID偏左移6位

*/

private final static long workerIdShift = sequenceBits;

/**

* 时间毫秒左移7位

*/

private final static long timestampLeftShift = sequenceBits + workerIdBits;

private final long workerId;

private long sequence = 0L;

private long lastTimestamp = -1L;

public IdWorker(final long workerId) {

if (workerId > maxWorkerId || workerId < 0) {

throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));

}

this.workerId = workerId;

}

public synchronized long nextId() {

long timestamp = this.timeGen();

if (timestamp < this.lastTimestamp) {

throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", this.lastTimestamp - timestamp));

}

if (this.lastTimestamp == timestamp) {

this.sequence = (this.sequence + 1) & sequenceMask;

if (this.sequence == 0) {

timestamp = this.tilNextMillis(this.lastTimestamp);

}

}

else {

this.sequence = 0;

}

this.lastTimestamp = timestamp;

return ((timestamp - twepoch << timestampLeftShift)) | (this.workerId << workerIdShift) | (this.sequence);

}

private long tilNextMillis(final long lastTimestamp) {

long timestamp = this.timeGen();

while (timestamp <= lastTimestamp) {

timestamp = this.timeGen();

}

return timestamp;

}

private long timeGen() {

return System.currentTimeMillis();

}

}

注意:本文归作者所有,未经作者允许,不得转载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值