java 47 lines · 8 steps

How to generate a ULID in Java

A ULID packs a millisecond timestamp and random entropy into a sortable, Crockford base32 string.

Explained by highlit
1public final class Ulid {
2 
3 private static final char[] ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ".toCharArray();
4 private static final SecureRandom RANDOM = new SecureRandom();
5 private static final int TIME_LENGTH = 10;
6 private static final int RANDOM_LENGTH = 16;
7 
8 private Ulid() {
9 }
10 
11 public static String generate() {
12 return generate(System.currentTimeMillis());
13 }
14 
15 public static String generate(long timestamp) {
16 if (timestamp < 0 || timestamp > 0xFFFFFFFFFFFFL) {
17 throw new IllegalArgumentException("timestamp out of ULID range");
18 }
19 char[] chars = new char[TIME_LENGTH + RANDOM_LENGTH];
20 encodeTime(timestamp, chars);
21 encodeRandom(chars);
22 return new String(chars);
23 }
24 
25 private static void encodeTime(long timestamp, char[] out) {
26 for (int i = TIME_LENGTH - 1; i >= 0; i--) {
27 out[i] = ENCODING[(int) (timestamp & 0x1F)];
28 timestamp >>>= 5;
29 }
30 }
31 
32 private static void encodeRandom(char[] out) {
33 byte[] entropy = new byte[10];
34 RANDOM.nextBytes(entropy);
35 long bits = 0L;
36 int available = 0;
37 int entropyIndex = 0;
38 for (int i = TIME_LENGTH; i < out.length; i++) {
39 if (available < 5) {
40 bits = (bits << 8) | (entropy[entropyIndex++] & 0xFFL);
41 available += 8;
42 }
43 available -= 5;
44 out[i] = ENCODING[(int) ((bits >>> available) & 0x1F)];
45 }
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Crockford's base32 alphabet omits I, L, O, and U to stay unambiguous when read by humans.
  2. 2Encoding five bits per character means bytes must be buffered and drained in 5-bit chunks.
  3. 3Putting the timestamp first makes ULIDs lexicographically sortable by creation time.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How to generate a ULID in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code