SnowflakeIdWorker
/**
* Twitter_Snowflake<br>
* SnowFlake的結(jié)構(gòu)如下(每部分用-分開(kāi)):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位標(biāo)識(shí),由于long基本類(lèi)型在Java中是帶符號(hào)的乐导,最高位是符號(hào)位躏吊,正數(shù)是0侥祭,負(fù)數(shù)是1秀存,所以id一般是正數(shù)挺邀,最高位是0<br>
* 41位時(shí)間截(毫秒級(jí))幢尚,注意瑰妄,41位時(shí)間截不是存儲(chǔ)當(dāng)前時(shí)間的時(shí)間截,而是存儲(chǔ)時(shí)間截的差值(當(dāng)前時(shí)間截 - 開(kāi)始時(shí)間截)
* 得到的值)骇扇,這里的的開(kāi)始時(shí)間截摔竿,一般是我們的id生成器開(kāi)始使用的時(shí)間,由我們程序來(lái)指定的(如下下面程序IdWorker類(lèi)的startTime屬性)少孝。41位的時(shí)間截继低,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的數(shù)據(jù)機(jī)器位稍走,可以部署在1024個(gè)節(jié)點(diǎn)袁翁,包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒內(nèi)的計(jì)數(shù)婿脸,12位的計(jì)數(shù)順序號(hào)支持每個(gè)節(jié)點(diǎn)每毫秒(同一機(jī)器粱胜,同一時(shí)間截)產(chǎn)生4096個(gè)ID序號(hào)<br>
* 加起來(lái)剛好64位,為一個(gè)Long型狐树。<br>
* SnowFlake的優(yōu)點(diǎn)是焙压,整體上按照時(shí)間自增排序,并且整個(gè)分布式系統(tǒng)內(nèi)不會(huì)產(chǎn)生ID碰撞(由數(shù)據(jù)中心ID和機(jī)器ID作區(qū)分),并且效率較高涯曲,經(jīng)測(cè)試野哭,SnowFlake每秒能夠產(chǎn)生26萬(wàn)ID左右。
*/
public class SnowflakeIdWorker {
// ==============================Fields===========================================
/**
* 開(kāi)始時(shí)間截 (2015-01-01)
*/
private final long twepoch = 1420041600000L;
/**
* 機(jī)器id所占的位數(shù)
*/
private final long workerIdBits = 5L;
/**
* 數(shù)據(jù)標(biāo)識(shí)id所占的位數(shù)
*/
private final long datacenterIdBits = 5L;
/**
* 支持的最大機(jī)器id幻件,結(jié)果是31 (這個(gè)移位算法可以很快的計(jì)算出幾位二進(jìn)制數(shù)所能表示的最大十進(jìn)制數(shù))
*/
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
/**
* 支持的最大數(shù)據(jù)標(biāo)識(shí)id拨黔,結(jié)果是31
*/
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/**
* 序列在id中占的位數(shù)
*/
private final long sequenceBits = 12L;
/**
* 機(jī)器ID向左移12位
*/
private final long workerIdShift = sequenceBits;
/**
* 數(shù)據(jù)標(biāo)識(shí)id向左移17位(12+5)
*/
private final long datacenterIdShift = sequenceBits + workerIdBits;
/**
* 時(shí)間截向左移22位(5+5+12)
*/
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/**
* 生成序列的掩碼,這里為4095 (0b111111111111=0xfff=4095)
*/
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/**
* 工作機(jī)器ID(0~31)
*/
private long workerId;
/**
* 數(shù)據(jù)中心ID(0~31)
*/
private long datacenterId;
/**
* 毫秒內(nèi)序列(0~4095)
*/
private long sequence = 0L;
/**
* 上次生成ID的時(shí)間截
*/
private long lastTimestamp = -1L;
//==============================Constructors=====================================
/**
* 構(gòu)造函數(shù)
*
* @param workerId 工作ID (0~31)
* @param datacenterId 數(shù)據(jù)中心ID (0~31)
*/
public SnowflakeIdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// ==============================Methods==========================================
/**
* 獲得下一個(gè)ID (該方法是線(xiàn)程安全的)
*
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
//如果當(dāng)前時(shí)間小于上一次ID生成的時(shí)間戳傲武,說(shuō)明系統(tǒng)時(shí)鐘回退過(guò)這個(gè)時(shí)候應(yīng)當(dāng)拋出異常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一時(shí)間生成的蓉驹,則進(jìn)行毫秒內(nèi)序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
//毫秒內(nèi)序列溢出
if (sequence == 0) {
//阻塞到下一個(gè)毫秒,獲得新的時(shí)間戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//時(shí)間戳改變城榛,毫秒內(nèi)序列重置
else {
sequence = 0L;
}
//上次生成ID的時(shí)間截
lastTimestamp = timestamp;
//移位并通過(guò)或運(yùn)算拼到一起組成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (datacenterId << datacenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}
/**
* 阻塞到下一個(gè)毫秒揪利,直到獲得新的時(shí)間戳
*
* @param lastTimestamp 上次生成ID的時(shí)間截
* @return 當(dāng)前時(shí)間戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 返回以毫秒為單位的當(dāng)前時(shí)間
*
* @return 當(dāng)前時(shí)間(毫秒)
*/
protected long timeGen() {
//優(yōu)化點(diǎn):高并發(fā)場(chǎng)景下System.currentTimeMillis()存在性能問(wèn)題(System.currentTimeMillis()是native方法,即獲取時(shí)間需要和操作系統(tǒng)進(jìn)行交互(涉及到用戶(hù)態(tài)與內(nèi)核態(tài)的切換)狠持,優(yōu)化引入SystemClock
//return System.currentTimeMillis();
return SystemClock.now();
}
}
SystemClock
import java.sql.Timestamp;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* 高并發(fā)場(chǎng)景下System.currentTimeMillis()的性能問(wèn)題的優(yōu)化
* <p><p>
* System.currentTimeMillis()的調(diào)用比new一個(gè)普通對(duì)象要耗時(shí)的多(具體耗時(shí)高出多少我還沒(méi)測(cè)試過(guò)疟位,有人說(shuō)是100倍左右)<p>
* System.currentTimeMillis()之所以慢是因?yàn)槿ジ到y(tǒng)打了一次交道<p>
* 后臺(tái)定時(shí)更新時(shí)鐘,JVM退出時(shí)喘垂,線(xiàn)程自動(dòng)回收<p>
* 10億:43410,206,210.72815533980582%<p>
* 1億:4699,29,162.0344827586207%<p>
* 1000萬(wàn):480,12,40.0%<p>
* 100萬(wàn):50,10,5.0%<p>
*/
public class SystemClock {
private final long period;
private final AtomicLong now;
ExecutorService executor = Executors.newSingleThreadExecutor();
//將當(dāng)前系統(tǒng)時(shí)間存于內(nèi)存中
private SystemClock(long period) {
this.period = period;
this.now = new AtomicLong(System.currentTimeMillis());
scheduleClockUpdating();
}
private static class InstanceHolder {
public static final SystemClock INSTANCE = new SystemClock(1);
}
private static SystemClock instance() {
return InstanceHolder.INSTANCE;
}
private void scheduleClockUpdating() {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "System Clock");
thread.setDaemon(true);
return thread;
}
});
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
now.set(System.currentTimeMillis());
}
// 每毫秒更新一次內(nèi)存時(shí)間
}, period, period, TimeUnit.MILLISECONDS);
}
private long currentTimeMillis() {
return now.get();
}
public static long now() {
return instance().currentTimeMillis();
}
public static String nowDate() {
return new Timestamp(instance().currentTimeMillis()).toString();
}
//耗時(shí):741毫秒
public static void main(String[] args) {
long start = System.currentTimeMillis();
SnowflakeIdWorker idWorker0 = new SnowflakeIdWorker(0, 0);
for (int i = 0; i < Integer.MAX_VALUE; i++) {
long id = SystemClock.now();
}
System.out.println("耗時(shí):" + (System.currentTimeMillis() - start));
}
//耗時(shí):61409毫秒
// public static void main(String[] args) {
// long start = System.currentTimeMillis();
// SnowflakeIdWorker idWorker0 = new SnowflakeIdWorker(0, 0);
// for (int i = 0; i < Integer.MAX_VALUE; i++) {
// long id = System.currentTimeMillis();
// }
// System.out.println("耗時(shí):" + (System.currentTimeMillis() - start));
// }
}