Last active
February 2, 2016 14:55
-
-
Save hiropppe/f92ec512d5bab210040a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IdWorker { | |
long workerBits = 5L; | |
long datacenterBits = 5L; | |
long sequenceBits = 12L; | |
long workerIdShift = sequenceBits; | |
long datacenterIdShift = sequenceBits + workerBits; | |
long timestampLeftShift = sequenceBits + workerBits + datacenterBits; | |
long sequenceMask = -1L ^ (-1L << sequenceBits); | |
final long baseepoc = 1288834974657L; | |
long sequence = 0; | |
long lastTimestamp = -1L; | |
public long nextId() { | |
long timestamp = System.currentTimeMillis(); | |
long timeId = timestamp - baseepoc; | |
long datacenterId = 1; | |
long workerId = 3; | |
if(timestamp == lastTimestamp) { | |
sequence = (sequence + 1) & sequenceMask; | |
} | |
else { | |
sequence = 0; | |
} | |
lastTimestamp = timestamp; | |
long id = ((timeId) << timestampLeftShift) | | |
(datacenterId << datacenterIdShift) | | |
(workerId << workerIdShift) + sequence; | |
return id; | |
} | |
public static void main(String...args) { | |
IdWorker w = new IdWorker(); | |
long id = w.nextId(); | |
System.out.println(id); | |
System.out.println(Long.toBinaryString(id)); | |
System.out.println(Long.toHexString(id)); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment