Back to Transmittable Thread Local

πŸŽ“ Developer Guide

docs/developer-guide-en.md

2.14.53.1 KB
Original Source

πŸŽ“ Developer Guide


<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <!-- END doctoc generated TOC please keep comment here to allow auto update -->

πŸ“Œ Framework/Middleware integration to TTL transmittance

TransmittableThreadLocal.Transmitter to capture all TTL values of current thread and replay them in another thread.

There are following methods:

  1. capture: capture all TTL values in current thread
  2. replay: replay the captured TTL values in the current thread, and return the backup TTL values before replay
  3. restore: restore TTL values before replay

Sample code:

java
// ===========================================================================
// Thread A
// ===========================================================================

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

// 1. capture all TTL values in current thread
final Object captured = TransmittableThreadLocal.Transmitter.capture();

// ===========================================================================
// Thread B
// ===========================================================================

// 2. replay the captured TTL values in current thread, and return the backup TTL values before replay
final Object backup = TransmittableThreadLocal.Transmitter.replay(captured);
try {
    // Your biz code, you can get the TTL value from here
    String value = context.get();
    ...
} finally {
    // 3. restore TTL values before replay
    TransmittableThreadLocal.Transmitter.restore(backup);
}

πŸ“š Related material

JDK core classes

Java Agent

Javassist

Maven Shade plugin