-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathUniqueId.java
More file actions
74 lines (63 loc) · 2.16 KB
/
Copy pathUniqueId.java
File metadata and controls
74 lines (63 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package uniq;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.eaio.uuid.UUIDGen;
public class UniqueId {
// Get the MAC address (i.e., the "node" from a UUID1)
private final long clockSeqAndNode = UUIDGen.getClockSeqAndNode();
private final byte[] node = new byte[]{
(byte)((clockSeqAndNode >> 40) & 0xff),
(byte)((clockSeqAndNode >> 32) & 0xff),
(byte)((clockSeqAndNode >> 24) & 0xff),
(byte)((clockSeqAndNode >> 16) & 0xff),
(byte)((clockSeqAndNode >> 8) & 0xff),
(byte)((clockSeqAndNode >> 0) & 0xff),
};
private final ThreadLocal<ByteBuffer> tlbb = new ThreadLocal<ByteBuffer>() {
@Override
public ByteBuffer initialValue() {
return ByteBuffer.allocate(16);
}
};
private volatile int seq;
private volatile long lastTimestamp;
private final Object lock = new Object();
private final int maxShort = (int)0xffff;
public byte[] getId() {
if(seq == maxShort) {
throw new RuntimeException("Too fast");
}
long time;
synchronized(lock) {
time = System.currentTimeMillis();
if(time != lastTimestamp) {
lastTimestamp = time;
seq = 0;
}
seq++;
ByteBuffer bb = tlbb.get();
bb.rewind();
bb.putLong(time);
bb.put(node);
bb.putShort((short)seq);
return bb.array();
}
}
public String getStringId() {
byte[] ba = getId();
ByteBuffer bb = ByteBuffer.wrap(ba);
long ts = bb.getLong();
int node_0 = bb.getInt();
short node_1 = bb.getShort();
short seq = bb.getShort();
return String.format("%016d-%s%s-%04d", ts, Integer.toHexString(node_0), Integer.toHexString(node_1), seq);
}
public static void main(String[] args) throws IOException {
UniqueId uid = new UniqueId();
int n = Integer.parseInt(args[0]);
for(int i=0; i<n; i++) {
System.out.write(uid.getId());
//System.out.println(uid.getStringId());
}
}
}