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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Crockford's base32 alphabet omits I, L, O, and U to stay unambiguous when read by humans.
- 2Encoding five bits per character means bytes must be buffered and drained in 5-bit chunks.
- 3Putting the timestamp first makes ULIDs lexicographically sortable by creation time.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-to-generate-a-ulid-in-java-explained-java-651e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.