1. Overview
Storing context during code execution is a common challenge. For instance, we might store security properties during a web request or keep traceability fields like transaction ID for logging or sharing across the system. To handle this, we can use ThreadLocal or InheritableThreadLocal fields. These classes provide a powerful container for our context while ensuring thread separation. However, these classes have limitations.
In this article, we’ll explore how to use TransmittableThreadLocal from the transmittable-thread-local library to overcome multithreading issues and safely manage context.
2. ThreadLocal Problem
We can use ThreadLocal to store the call context. However, we won’t get the value if we try to access it from another thread. Let’s look at a quick example to illustrate this issue:
@Test
void givenThreadLocal_whenTryingToGetValueFromAnotherThread_thenNullIsExpected() {
ThreadLocal<String> transactionID = new ThreadLocal<>();
transactionID.set(UUID.randomUUID().toString());
new Thread(() -> assertNull(transactionID.get())).start();
}
We set up the UUID in the main thread and retrieve it in a new thread. As expected, we didn’t get the value.
3. InheritableThreadLocal Problem
By using InheritableThreadLocal, we avoid issues with multithreaded access to the context. We can access the stored values from any thread created under the main thread. However, we still may have limitations here. If we modify the context during the process, the updated value won’t appear in parallel threads.
Let’s see how it works:
@Test
void givenInheritableThreadLocal_whenChangeTheTransactionIdAfterSubmissionToThreadPool_thenNewValueWillNotBeAvailableInParallelThread() {
String firstTransactionIDValue = UUID.randomUUID().toString();
InheritableThreadLocal<String> transactionID = new InheritableThreadLocal<>();
transactionID.set(firstTransactionIDValue);
Runnable task = () -> assertEquals(firstTransactionIDValue, transactionID.get());
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(task);
String secondTransactionIDValue = UUID.randomUUID().toString();
Runnable task2 = () -> assertNotEquals(secondTransactionIDValue, transactionID.get());
transactionID.set(secondTransactionIDValue);
executorService.submit(task2);
executorService.shutdown();
}
We create a UUID value and set it in the InheritableThreadLocal variable. Then, we check the value in a separate thread running in the thread pool executor. We confirm that the value inside the thread pool matched the one set in the main thread. Next, we update the variable and check the value again in the thread pool. We retrieve the previous value this time, and our update is ignored.
4. Using the transmittable-thread-local Library
TransmittableThreadLocal, a class from an open-source transmittable-thread-local library developed by Alibaba, extends InheritableThreadLocal. It enables value sharing across threads, even with thread pools. We can use it to ensure context changes stay synchronized across all threads during execution.
4.1. Dependencies
Let’s start by adding the necessary dependencies:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>2.14.5</version>
</dependency>
After adding this dependency, we can use the TransmittableThreadLocal classes.
4.2. One Parallel Thread Example
In the first example, we’ll check if our TransmittableThreadLocal variable can store values across threads:
@Test
void givenTransmittableThreadLocal_whenTryingToGetValueFromAnotherThread_thenValueIsPresent() {
TransmittableThreadLocal<String> transactionID = new TransmittableThreadLocal<>();
transactionID.set(UUID.randomUUID().toString());
new Thread(() -> assertNotNull(transactionID.get())).start();
}
We create a transaction ID and successfully retrieve its value in another thread.
4.3. ExecutorService Example
In the next example, we’ll create a TransmittableThreadLocal variable with a transaction ID. Then, we’ll submit it to the thread pool and modify it during the process:
@Test
void givenTransmittableThreadLocal_whenChangeTheTransactionIdAfterSubmissionToThreadPool_thenNewValueWillBeAvailableInParallelThread() {
String firstTransactionIDValue = UUID.randomUUID().toString();
String secondTransactionIDValue = UUID.randomUUID().toString();
TransmittableThreadLocal<String> transactionID = new TransmittableThreadLocal<>();
transactionID.set(firstTransactionIDValue);
Runnable task = () -> assertEquals(firstTransactionIDValue, transactionID.get());
Runnable task2 = () -> assertEquals(secondTransactionIDValue, transactionID.get());
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(TtlRunnable.get(task));
transactionID.set(secondTransactionIDValue);
executorService.submit(TtlRunnable.get(task2));
executorService.shutdown();
}
We can see that the initial and modified values were retrieved successfully. We use TtlRunnable here. This class allows us to transfer the thread-local state between threads in the thread pool.
4.4. Parallel Streams Example
Another interesting case for using the TransmittableThreadLocal variable involves the parallel streams. When we have multiple items in our stream, it may execute on a ForkJoinPool. This can lead to issues with a shared context across all threads in the pool. Let’s see how we can solve this challenge with TransmittableThreadLocal:
@Test
void givenTransmittableThreadLocal_whenChangeTheTransactionIdAfterParallelStreamAlreadyProcessed_thenNewValueWillBeAvailableInTheSecondParallelStream() {
String firstTransactionIDValue = UUID.randomUUID().toString();
String secondTransactionIDValue = UUID.randomUUID().toString();
TransmittableThreadLocal<String> transactionID = new TransmittableThreadLocal<>();
transactionID.set(firstTransactionIDValue);
TtlExecutors.getTtlExecutorService(new ForkJoinPool(4))
.submit(
() -> List.of(1, 2, 3, 4, 5)
.parallelStream()
.forEach(i -> assertEquals(firstTransactionIDValue, transactionID.get())));
transactionID.set(secondTransactionIDValue);
TtlExecutors.getTtlExecutorService(new ForkJoinPool(4))
.submit(
() -> List.of(1, 2, 3, 4, 5)
.parallelStream()
.forEach(i -> assertEquals(secondTransactionIDValue, transactionID.get())));
}
Since we can’t modify the shared thread pool used for all parallel threads, we need to run our stream inside a separate ThreadPoolExecutor. We use the TtlExecutors wrapper to synchronize the context between the main thread and all the threads used during the parallel stream execution.
In our experiment, we created and modified the transaction ID within the main thread. Additionally, we accessed this transaction ID from the parallel stream. We successfully retrieved both the initial and the modified values.
5. Conclusion
In this tutorial, we explored different implementations of thread-local variables. We choose one based on our needs.
Simple ThreadLocal variables are useful for single-thread execution with a specific context. We use InheritableThreadLocal when we need to share the context between multiple inherited threads. Finally, we can choose TransmittableThreadLocal from the transmittable-thread-local library to synchronize context changes across threads within thread pools.
As always, the code is available over on GitHub.