📖 English Documentation | 📖 中文文档
- 🔧 Functions
- 🎨 Requirements
- 👥 User Guide
- 🔌 Java API Docs
- 🍪 Maven Dependency
- 🔨 About compilation, build and dev
- 🗿 More Documentation
- 📚 Related Resources
- 👷 Contributors
👉 The missing Java™ std lib(simple & 0-dependency) for framework/middleware,
provide an enhanced InheritableThreadLocal
that transmits ThreadLocal
value between threads even using thread pooling components.
Support Java
15/14/13/12/11/10/9/8/7/6.
Class InheritableThreadLocal
in JDK
can transmit value to child thread from parent thread.
But when use thread pool, thread is cached up and used repeatedly. Transmitting value from parent thread to child thread has no meaning. Application need transmit value from the time task is created to the time task is executed.
If you have problem or question, please submit Issue or play fork and pull request dance.
The Requirements listed below is also why I sort out TransmittableThreadLocal
in my work.
- Application container or high layer framework transmit information to low layer sdk.
- Transmit context to logging without application code aware.
// set in parent thread
TransmittableThreadLocal<String> context = new TransmittableThreadLocal<String>();
context.set("value-set-in-parent");
// =====================================================
// read in child thread, value is "value-set-in-parent"
String value = context.get();
# See the executable demo SimpleDemo.kt
with full source code.
This is the function of class InheritableThreadLocal
, should use class InheritableThreadLocal
instead.
But when use thread pool, thread is cached up and used repeatedly. Transmitting value from parent thread to child thread has no meaning. Application need transmit value from the time task is created to the point task is executed.
The solution is below usage.
Decorate input Runnable
and Callable
by TtlRunnable
and TtlCallable
.
Sample code:
TransmittableThreadLocal<String> parent = new TransmittableThreadLocal<String>();
parent.set("value-set-in-parent");
Runnable task = new RunnableTask();
// extra work, create decorated ttlRunnable object
Runnable ttlRunnable = TtlRunnable.get(task);
executorService.submit(ttlRunnable);
// =====================================================
// read in task, value is "value-set-in-parent"
String value = parent.get();
above code show how to dealing with Runnable
, Callable
is similar:
TransmittableThreadLocal<String> parent = new TransmittableThreadLocal<String>();
parent.set("value-set-in-parent");
Callable call = new CallableTask();
// extra work, create decorated ttlCallable object
Callable ttlCallable = TtlCallable.get(call);
executorService.submit(ttlCallable);
// =====================================================
// read in call, value is "value-set-in-parent"
String value = parent.get();
# See the executable demo TtlWrapperDemo.kt
with full source code.
Eliminating the work of Runnable
and Callable
Decoration every time it is submitted to thread pool. This work can completed in the thread pool.
Use util class
com.alibaba.ttl.threadpool.TtlExecutors
to decorate thread pool.
Util class com.alibaba.ttl.threadpool.TtlExecutors
has below methods:
getTtlExecutor
: decorate interfaceExecutor
getTtlExecutorService
: decorate interfaceExecutorService
getTtlScheduledExecutorService
: decorate interfaceScheduledExecutorService
Sample code:
ExecutorService executorService = ...
// extra work, create decorated executorService object
executorService = TtlExecutors.getTtlExecutorService(executorService);
TransmittableThreadLocal<String> parent = new TransmittableThreadLocal<String>();
parent.set("value-set-in-parent");
Runnable task = new RunnableTask();
Callable call = new CallableTask();
executorService.submit(task);
executorService.submit(call);
// =====================================================
// read in Task or Callable, value is "value-set-in-parent"
String value = parent.get();
# See the executable demo TtlExecutorWrapperDemo.kt
with full source code.
In this usage, transmission is transparent(no decoration operation).
Sample code:
// ## 1. upper layer logic of framework ##
TransmittableThreadLocal<String> context = new TransmittableThreadLocal<String>();
context.set("value-set-in-parent");
// ## 2. biz logic ##
ExecutorService executorService = Executors.newFixedThreadPool(3);
Runnable task = new RunnableTask();
Callable call = new CallableTask();
executorService.submit(task);
executorService.submit(call);
// ## 3. underlayer logic of framework ##
// read in Task or Callable, value is "value-set-in-parent"
String value = context.get();
# See the executable demo AgentDemo.kt
with full source code, run demo by the script scripts/run-agent-demo.sh
.
At present, TTL
agent has decorated below JDK
execution components(aka. thread pool) implementation:
java.util.concurrent.ThreadPoolExecutor
andjava.util.concurrent.ScheduledThreadPoolExecutor
- decoration implementation code is in
TtlExecutorTransformlet.java
.
- decoration implementation code is in
java.util.concurrent.ForkJoinTask
(corresponding execution component isjava.util.concurrent.ForkJoinPool
)- decoration implementation code is in
TtlForkJoinTransformlet.java
, supports since version2.5.1
. - NOTE:
CompletableFuture
and (parallel)Stream
introduced in Java 8 is executed throughForkJoinPool
underneath, so after supportingForkJoinPool
,TTL
also supportsCompletableFuture
andStream
transparently. 🎉
- decoration implementation code is in
java.util.TimerTask
(corresponding execution component isjava.util.Timer
)- decoration implementation code is in
TtlTimerTaskTransformlet.java
, supports since version2.7.0
. - NOTE: Since version
2.11.2
decoration forTimerTask
default is enable (because correctness is first concern, not the best practice like "It is not recommended to useTimerTask
" :); before version2.11.1
default is disable. - enabled/disable by agent argument
ttl.agent.enable.timer.task
:-javaagent:path/to/transmittable-thread-local-2.x.x.jar=ttl.agent.enable.timer.task:true
-javaagent:path/to/transmittable-thread-local-2.x.x.jar=ttl.agent.enable.timer.task:false
- more info about
TTL
agent arguments, see the javadoc ofTtlAgent.java
.
- decoration implementation code is in
Add start options on Java command:
-javaagent:path/to/transmittable-thread-local-2.x.x.jar
NOTE:
- Because TTL agent modified the
JDK
std lib classes, make code refer from std lib class to the TTL classes, so the TTL Agent jar must be added toboot classpath
. - Since
v2.6.0
, TTL agent jar will auto add self toboot classpath
. But you should NOT modify the downloaded TTL jar file name in the maven repo(eg:transmittable-thread-local-2.x.x.jar
).- if you modified the downloaded TTL jar file name(eg:
ttl-foo-name-changed.jar
), you must add TTL agent jar toboot classpath
manually by java option-Xbootclasspath/a:path/to/ttl-foo-name-changed.jar
.
- if you modified the downloaded TTL jar file name(eg:
The implementation of auto adding self agent jar to boot classpath
use the Boot-Class-Path
property of manifest file(META-INF/MANIFEST.MF
) in the TTL Java Agent Jar:
Boot-Class-Path
A list of paths to be searched by the bootstrap class loader. Paths represent directories or libraries (commonly referred to as JAR or zip libraries on many platforms). These paths are searched by the bootstrap class loader after the platform specific mechanisms of locating a class have failed. Paths are searched in the order listed.
More info:
Java Agent Specification
-JavaDoc
文档- JAR File Specification - JAR Manifest
- Working with Manifest Files - The Java™ TutorialsHide
Java command example:
java -javaagent:transmittable-thread-local-2.x.x.jar \
-cp classes \
com.alibaba.demo.ttl.agent.AgentDemo
or
# if changed the TTL jar file name or the TTL version is before 2.6.0,
# should set argument -Xbootclasspath explicitly.
java -javaagent:path/to/ttl-foo-name-changed.jar \
-Xbootclasspath/a:path/to/ttl-foo-name-changed.jar \
-cp classes \
com.alibaba.demo.ttl.agent.AgentDemo
Run the script scripts/run-agent-demo.sh
to start demo of "Use Java Agent to decorate thread pool implementation class".
The current version Java API documentation: https://alibaba.github.io/transmittable-thread-local/apidocs/
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>2.11.5</version>
</dependency>
Check available version at search.maven.org.
Compilation/build environment require JDK 8~11
; Compilation can be performed in the normal way of Maven
.
# The project already contains Maven
that satisfied the required version, directly run mvnw
in the project root directory; there is no need to manually install Maven
by yourself.
# Run test case
./mvnw test
# Compile and package
./mvnw package
# Run test case, compile and package, install TTL library to local Maven
./mvnw install
##################################################
# If you use `Maven` installed by yourself, the version requirement: maven 3.3.9+
mvn install
If you use IDE
to develop (such as IntelliJ IDEA
), note that:
open the pom4ide.xml
file in the root directory of the project instead of pom.xml
via IDE
;
To avoid IDE
complain using JDK 8
standard library classes not found.
The reason that IDE
support is not good / have to change a POM
file, is:
The code implementation of TTL
uses the JDK 8
standard library class, but it is compiled into a Java 6
version class files.
- Jerry Lee <oldratlee at gmail dot com> @oldratlee
- Yang Fang <snoop.fy at gmail dot com> @driventokill
- Zava Xu <zava.kid at gmail dot com> @zavakid
- wuwen <wuwen.55 at aliyun dot com> @wuwen5
- Xiaowei Shi <179969622 at qq dot com> @xwshiustc
- David Dai <351450944 at qq dot com> @LNAmp
- Your name here :-)