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
@RestController @RequestMapping("/api/reports") public class ReportController {
Header-driven endpoints in a Spring controller
rest api
request headers
dependency injection
Intermediate
7 steps
java
public final class CaseConverter { private static final Pattern CAMEL_BOUNDARY = Pattern.compile("([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])");
Converting camelCase to snake_case in Java
regex
string-manipulation
utility-class
Intermediate
7 steps
java
@Component public class RegionCacheWarmer implements SmartInitializingSingleton { private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
Warming a Spring cache at startup
caching
startup-hook
dependency-injection
Intermediate
7 steps
java
public final class EmailNormalizer { private static final Pattern EMAIL_PATTERN = Pattern.compile( "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
Normalizing email addresses in Java
validation
regex
normalization
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") @RequiredArgsConstructor public class ProductBatchController {
Batch JSON Merge Patch in Spring
json-merge-patch
rest-api
partial-update
Intermediate
8 steps
java
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
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.