11package net .sharksystem .asap ;
22
3+ import java .util .Random ;
4+
35public 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}
0 commit comments