Skip to content

Commit 0f57873

Browse files
committed
make my own UUID
1 parent 9fc0f48 commit 0f57873

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

src/net/sharksystem/asap/ASAP.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package net.sharksystem.asap;
22

3+
import java.util.Random;
4+
35
public class ASAP {
46
public static final int INITIAL_ERA = 0;
57
public static final int MAX_ERA = Integer.MAX_VALUE;
@@ -17,4 +19,78 @@ public static int previousEra(int workingEra) {
1719
}
1820
return workingEra-1;
1921
}
22+
23+
/**
24+
* produces a unique id - is made up by current time in millis added with some random digits.
25+
* @return
26+
*/
27+
public static String createUniqueID() {
28+
long now = System.currentTimeMillis();
29+
30+
/* now is a 64 bit value. Actually, only 63 bits are relevant because it is positive value.
31+
Moreover, we are already in the 21. century - could reduce bit even more. We ignore that obvious fact
32+
at first.
33+
34+
Calcuations: 2^64 = 1,8.. * 10^19; we take a..z and A..Z and 0..9 -> 62 digits
35+
62^11 = 5,2.. * 10^19 we need 11 digits
36+
*/
37+
38+
int randomDigits = 3;
39+
int timeDigits = 11;
40+
int digits = timeDigits + randomDigits;
41+
int basis = 62;
42+
43+
/*
44+
0..9 --> 0..9
45+
10..35 -> a..z
46+
36..61 -> A..Z
47+
*/
48+
49+
char[] idChars = new char[digits];
50+
// init
51+
for(int i = 0; i < digits; i++) idChars[i] = '0';
52+
53+
// let's fill it
54+
int i = 0;
55+
long rest = 0;
56+
while(now > 0) {
57+
rest = now % basis; // rest is number [0,63]
58+
now /= basis;
59+
60+
idChars[i++] = ASAP.int2charID((int) rest);
61+
}
62+
63+
// set index
64+
i = timeDigits;
65+
66+
// random digits
67+
long rValue = now + rest;
68+
Random random = new Random(rValue);
69+
for(int j = 0; j < randomDigits; j++) {
70+
int r = random.nextInt(basis);
71+
idChars[i++] = ASAP.int2charID(r);
72+
rValue = (rValue * r) % basis;
73+
random.setSeed(rValue);
74+
}
75+
76+
return new String(idChars);
77+
}
78+
79+
private static char int2charID(int value) {
80+
// convert value into valid values;
81+
// 0..9 -> 0..9
82+
if(value <= 9) {
83+
return (char)((int)'0' + value);
84+
} else {
85+
value -= 10;
86+
// a..z
87+
if(value <= 25) {
88+
return (char)((int)'a' + value);
89+
} else {
90+
// A..Z
91+
value -= 26;
92+
return (char)((int)'A' + value);
93+
}
94+
}
95+
}
2096
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package net.sharksystem.asap;
2+
3+
import org.junit.Test;
4+
5+
public class BasisMethodsTests {
6+
7+
@Test
8+
public void asapID() throws InterruptedException {
9+
for(int i = 0; i < 10; i++) {
10+
System.out.println(ASAP.createUniqueID());
11+
Thread.sleep(2);
12+
}
13+
}
14+
}

0 commit comments

Comments
 (0)