gitmyhub

transmittable-thread-local

Java β˜… 8.3k updated 1d ago

πŸ“Œ a missing Java std lib(simple & 0-dependency) for framework/middleware, provide an enhanced InheritableThreadLocal that transmits values between threads even using thread pooling components.

This is a small Java library from Alibaba that solves a specific problem with thread-local storage in Java applications. In Java, developers often store per-request information (like a user ID or trace ID) in a structure called a ThreadLocal, which keeps that data tied to the current thread. Java also has a built-in InheritableThreadLocal that passes that data to child threads, but it breaks down when thread pools are involved, because pooled threads are created once and reused many times rather than spawned fresh for each task.

This library provides a class called TransmittableThreadLocal (TTL) that fills that gap. When a task is submitted to a thread pool, TTL captures the current ThreadLocal values from the submitting thread and makes them available inside the task when it runs on a pooled thread. The library has zero external dependencies and is around 1000 lines of code, making it very lightweight to add to a project.

There are three ways to use it: wrap individual tasks (Runnable or Callable) with a TTL-aware wrapper before submitting them to a pool, wrap the thread pool itself so all tasks go through TTL automatically, or use a Java Agent that patches the standard JDK thread pool classes at startup without any code changes in the application.

Typical use cases mentioned in the documentation include distributed tracing systems (where a trace ID must follow a request through all async work), log context collection, request-scoped caches, and passing configuration from a framework layer down to an SDK. The library supports Java 6 through 21 depending on the version used. The full README is longer than what was shown.