Skip to content

Latest commit

 

History

History
286 lines (199 loc) · 13.4 KB

README-EN.md

File metadata and controls

286 lines (199 loc) · 13.4 KB

📌 Transmittable ThreadLocal(TTL) 📌

Build Status Windows Build Status Coverage Status Maintainability
License Javadocs Maven Central GitHub release
Join the chat at https://gitter.im/alibaba/transmittable-thread-local GitHub issues Percentage of issues still open Average time to resolve an issue

📖 English Documentation | 📖 中文文档



🔧 Functions

👉 The missing std Java™ lib(simple & 0-dependency) for framework/middleware, transmitting ThreadLocal value between threads even using thread pooling components. Support Java 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.

🎨 Requirements

The Requirements listed below is also why I sort out TTL in my work.

  • Application container or high layer framework transmit information to low layer sdk.
  • Transmit context to logging without application code aware.

👥 User Guide

1. simple usage

// set in parent thread
TransmittableThreadLocal<String> parent = new TransmittableThreadLocal<String>();
parent.set("value-set-in-parent");

// =====================================================

// read in child thread, value is "value-set-in-parent"
String value = parent.get();

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.

2. Transmit value even using thread pool

2.1 Decorate Runnable and Callable

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 Task("1");
// 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 Call("1");
// 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();

2.2 Decorate thread pool

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 interface Executor
  • getTtlExecutorService: decorate interface ExecutorService
  • getTtlScheduledExecutorService: decorate interface ScheduledExecutorService

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 Task("1");
Callable call = new Call("2");
executorService.submit(task);
executorService.submit(call);

// =====================================================

// read in Task or Callable, value is "value-set-in-parent"
String value = parent.get();

2.3 Use Java Agent to decorate thread pool implementation class

In this usage, transmission is transparent(no decoration operation).

Sample code:

ExecutorService executorService = Executors.newFixedThreadPool(3);

Runnable task = new Task("1");
Callable call = new Call("2");
executorService.submit(task);
executorService.submit(call);

// =====================================================

// read in Task or Callable, value is "value-set-in-parent"
String value = parent.get();

See demo AgentDemo.kt.

At present, TTL agent has decorated below JDK thread pool implementation:

  • java.util.concurrent.ThreadPoolExecutor and java.util.concurrent.ScheduledThreadPoolExecutor
    decoration implemetation code is in TtlExecutorTransformlet.java
  • java.util.concurrent.ForkJoinTask(corresponding thread pool is java.util.concurrent.ForkJoinPool
    decoration implemetation code is in TtlForkJoinTransformlet.java
  • java.util.TimerTask(corresponding thread pool is java.util.Timer
    decoration implemetation code is in TtlTimerTaskTransformlet.java
    NOTE: decoration for TimerTask default is disable, enabled by agent argument ttl.agent.enable.timer.task: -javaagent:path/to/transmittable-thread-local-2.x.x.jar:ttl.agent.enable.timer.task:true.
    more info about TTL agent arguments, see the javadoc of TtlAgent.java.

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 to boot classpath.
  • Since v2.6.0, TTL agent jar will auto add self to boot 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 to boot classpath manually by java option -Xbootclasspath/a:path/to/ttl-foo-name-changed.jar.

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 command example:

java -javaagent:transmittable-thread-local-2.x.x.jar \
    -cp classes \
    com.alibaba.ttl.threadpool.agent.demo.AgentDemo

or

java -javaagent:path/to/ttl-foo-name-changed.jar \
    -Xbootclasspath/a:path/to/ttl-foo-name-changed.jar \
    -cp classes \
    com.alibaba.ttl.threadpool.agent.demo.AgentDemo

Run the script scripts/run-agent-demo.sh to start demo of "Use Java Agent to decorate thread pool implementation class".

🔌 Java API Docs

The current version Java API documentation: http://alibaba.github.io/transmittable-thread-local/apidocs/

🍪 Maven dependency

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>transmittable-thread-local</artifactId>
    <version>2.7.0</version>
</dependency>

Check available version at search.maven.org.

🗿 More documentation

📚 Related resources

JDK core classes

Java Agent

Javassist

👷 Contributors

  • Jerry Lee <oldratlee at gmail dot com> @oldratlee
  • Yang Fang <snoop.fy at gmail dot com> @driventokill
  • 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 :-)